python Django错误admin.E202 'stamm.Workplan'没有外键到'quiry. costing',多对多关系中的内联模型

g6ll5ycj  于 2023-01-29  发布在  Python
关注(0)|答案(2)|浏览(122)

我挣扎与以下问题:
我创建了两个应用程序,“stamm”和“inquiry”。在第一个应用程序“stamm”中,我有模型Workplan。在第二个应用程序“inquiry”中,我有模型Costing。我通过Costing模型下的直通模型“CostingWorkplan”使用M2M关系。然后我想从Workplan向CostingAdmin添加TabularInline。当我这样做时,我收到错误消息
〈class '查询.管理.工作计划内联'〉:(admin.E202)“stamm.工作计划”没有“查询.成本计算”的外键。
我检查了几个有类似问题的线程,但无法摆脱它。我忽略了什么吗?
下面是我的Python代码:

# stamm.models.py

class Workplan(model.Model):
    some_fields = ...

# enquiry.models.py

from stamm.models import Workplan

class Costing(model.Model):
    some_fields = ...
    costing_workplan = models.ManyToManyField(Workplan, through='CostingWorkplan')

class CostingWorkplan(models.Model):
    workplan = models.ForeignKey(Workplan, on_delete=models.RESTRICT)
    costing = models.ForeignKey(Costing, on_delete=models.RESTRICT)

# enquiry.admin.py
from .models import Costing
from stamm.models import Workplan

class WorkplanInline(admin.TabularInline):
    model = Workplan

@admin.register(Costing)
class CostingAdmin(admin.ModelAdmin):
    inlines = (WorkplanInline, )
balp4ylt

balp4ylt1#

昨天经过几个小时的研究、阅读和测试,我找到了答案。
我在使用多对多模型的内联模型的文档中仔细阅读了一些重要的细节。
重要的关键是更换

class WorkplanInline(admin.TabularInline):
    model = Workplan

class WorkplanInline(admin.TabularInline):
    model = Costing.costing_workplan.through

您可以在ModelAdmin文档中的“使用多对多模型”一节中阅读更多相关信息:(网址:https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.模型管理员)

8ehkhllq

8ehkhllq2#

WorkplanCosting也可以内联CostingWorkplan,如下所示;

class CostingWorkplanInline(admin.TabularInline):
    model = CostingWorkplan

@admin.register(Workplan)
class WorkplanAdmin(admin.ModelAdmin):
    inlines = (CostingWorkplanInline,)

@admin.register(Costing)
class CostingAdmin(admin.ModelAdmin):
    inlines = (CostingWorkplanInline,)

相关问题