gpt4 book ai didi

python - 如何在 models.py 文件中正确定义 ManyToMany 字段

转载 作者:太空宇宙 更新时间:2023-11-03 18:55:52 25 4
gpt4 key购买 nike

在我的 Django 应用程序中,我有以下 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/ 的指导下在 Host 类中添加了作业分配。我能够毫无问题地添加主机(从管理页面),但是当我尝试添加作业时,出现以下错误:

Exception at /admin/Minion/job/add
<class 'Minion.models.Host'> has no ForeignKey to <class 'Minion.models.Job'>

我也尝试向 Job 类添加 ManyToManyField 分配,但它告诉我名称 Host 未定义。有谁知道我可以做些什么来使这个字段正常运行?预先感谢您的帮助。

最佳答案

您需要在admin.py中为ManyToMany声明inlines

检查the documentation了解如何声明内联

类似这样的事情:

class JobInline(admin.TabularInline):
model = Host.jobs.through

关于python - 如何在 models.py 文件中正确定义 ManyToMany 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17277772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com