如何在models.py文件中正确定义ManyToMany字段 [英] how to properly define a ManyToMany field in the models.py file
问题描述
在我的Django应用程序中,我有以下models.py:
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)
我在主机类中添加了作业分配,其中包括 https:/ /docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/ 。我可以添加主机没有问题(从管理页面),但是当我尝试添加一个工作我得到以下错误:
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'>
我尝试添加一个ManyToManyField作业到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.
推荐答案
您需要声明 inlines
在 ManyToMany
在 admin.py
检查文档申报内容
这样的东西:
class JobInline(admin.TabularInline):
model = Host.jobs.through
这篇关于如何在models.py文件中正确定义ManyToMany字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!