python 管理模型中缺少外键?

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

尝试更新数据库时出现以下错误:
类“艺术数据库管理员角色内联”:(admin.E202)“artdb.Role”没有指向“artdb.Person”的外键
我想在Person和Role之间建立多对多的关系
model.py (not 显示所有类):

class Person(models.Model):
    mail=models.EmailField()
    firstName=models.CharField(max_length=200)
    lastName=models.CharField(max_length=200)
    phoneNumber=PhoneNumberField()
    streetAdress=models.CharField(max_length=200)
    zipcode=models.CharField(max_length=200)
    city=models.CharField(max_length=200,default="Göteborg")
    country=models.CharField(max_length=200,default="Sweden")
    
    def __str__(self):
        return "%s %s" % (self.firstName,self.lastName)

    class Meta:
        ordering = ('firstName','lastName')

class Role(models.Model):
    role=models.CharField(max_length=200)
    person=models.ManyToManyField(Person)
    
    def __str__(self):
        return self.role

    class Meta:
        ordering = ('role',)

admin.py (not 显示所有类):

from django.contrib import admin
from .models import Role
from .models import Address
from .models import Date
from .models import Person
from .models import Name

# Register your models here.

admin.site.register(Role)
admin.site.register(Address)
admin.site.register(Date)
admin.site.register(Name)
admin.site.register(Person)

class RoleInline(admin.TabularInline):
    model=Role
    extra=3

class PersonInline(admin.ModelAdmin):
    fieldsets=[
        (None,{'fields': ['mail','firstName','lastName','phoneNumber','streetAdress','zipcode','city','country']}),
    ]
    inlines = [RoleInline]
    search_fields = ['firstName']

#admin.site.register(Name,NameInline)
admin.site.register(Person,PersonInline)

它以前运行过manage.pymakemigrations artdb,我没有看到模型中的错误。

oxf4rvwz

oxf4rvwz1#

根据TabularInlineManytoMany关系的文档,您的RoleInline模型错误

model = Role.persons.through
tjvv9vkg

tjvv9vkg2#

您需要使用model=Role.person.through而不是model=Role,如下所示:

class RoleInline(admin.TabularInline):
    # model=Role
    model=Role.person.through # Here
    extra=3

相关问题