问题
In my Django app I have the following models.py:
from django.db import models
import datetime
class Job(models.Model):
name = models.CharField(max_length = 250, null = False)
user = models.CharField(max_length = 30, null = False)
command = models.CharField(max_length = 1000, null = False)
whenToRun = models.DateTimeField('Run Date', null = False)
output = models.CharField(max_length = 100000, null = True)
class Host(models.Model):
jobs = models.ManyToManyField(Job, blank = True)
name = models.CharField(max_length = 100, null = False)
hasRun = models.BooleanField(default = False)
I added the jobs assignment in the Host class with guidance from https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/. I was able to add Hosts in with no problem (from the admin page) but when I tried to add in a Job I got the following error:
Exception at /admin/Minion/job/add
<class 'Minion.models.Host'> has no ForeignKey to <class 'Minion.models.Job'>
I tried to add a ManyToManyField assignment to the Job class as well but it told me that the name Host was undefined. Does anyone know what I can do to make this field function properly? Thanks in advance for any help.
回答1:
You need to declare inlines
for ManyToMany
in admin.py
Check the documentation for how to declare inlines
Something like this:
class JobInline(admin.TabularInline):
model = Host.jobs.through
来源:https://stackoverflow.com/questions/17277772/how-to-properly-define-a-manytomany-field-in-the-models-py-file