我对如何在Django中建模关系感到困惑,以便可以在Django Admin中进行内联编辑。
让我解释一下这个场景。
我有一个客户模型和一个地址模型。在客户模型中,我有一个OneToOneField关系,一次性用于计费,一次用于送货地址。
class Address(models.Model):
pass
class Employee(models.Model):
billing_address = models.OneToOneField(Address)
shipping_address = models.OneToOneField(Address)
# Many more such fields
现在有了这个模型,没有简单的方法可以让它们在Admin中内联。我试过以下
class AddressInline(admin.TabularInline):
model = Address
class Customer(admin.ModelAdmin):
inlines = [AddressInline, ]
我一直收到错误,
<class 'employee.admin.AddressInline'>: (admin.E202) 'employee.Address' has no ForeignKey to 'employee.Customer'.
现在我知道还有其他类似的错误。即。 Use OneToOneField inlined in Django Admin和Django admin - OneToOneField inline throws "has no ForeignKey" exception
但我认为我的问题略有不同,以保证这篇文章。请帮忙!
答案 0 :(得分:2)
models.py
class BillingAddress(models.Model):
employee = models.OneToOneField(to=Employee, related_name='billing_address')
class Employee(models.Model):
# Many more such fields
admin.py
class AddressInline(admin.TabularInline):
model = BillingAddress
extra = 1
@admin.register(Employee)
class EmployeeAdmin(admin.ModelAdmin):
inlines = [AddressInline, ]
models.py
class Address(models.Model):
name = models.CharField(max_length=250)
employee = models.ForeignKey(to=Employee, related_name='addresses')
class Employee(models.Model):
# Many more such fields
admin.py
class AddressInline(admin.TabularInline):
model = Address
@admin.register(Employee)
class EmployeeAdmin(admin.ModelAdmin):
inlines = [AddressInline, ]
完整示例:
models.py
class Company(models.Model):
pass
class CompanyScheduler(models.Model):
company = models.OneToOneField(
to=Company,
related_name='scheduling',
on_delete=models.CASCADE,
)
start = models.DateField()
finish = models.DateField()
admin.py
class CompanySchedulerInLine(admin.TabularInline):
model = CompanySchedulerInLine
extra = 1
@admin.register(CompanyModelAdmin)
class CompanyModelAdmin(admin.ModelAdmin):
inlines = [
SchedulerInLine,
]
界面