我有一些表可以通过外键在单个相关表中共享信息。这些关系按预期工作,但是,我试图弄清楚如何自动填充随后用于过滤结果的字段。我希望下面的示例能够说明我正在尝试做的事情。
在模型中:
class UtilType(models.Model):
name = models.CharField()
description = models.CharField()
# following boolean fields used to filter table
is_address = models.BooleanField(default=False)
is_phone = models.BooleanField(default=False)
is_email = models.BooleanField(default=False)
is_domain = models.BooleanField(default=False)
class Address(models.Model):
address_type = models.ForeignKey(
UtilType,
on_delete=models.SET_NULL,
blank=True,
null=True,
related_name="addresses",
limit_choices_to={'is_address': True}
)
class PhoneType(models.Model):
phone_type = models.ForeignKey(
UtilType,
on_delete=models.SET_NULL,
blank=True,
null=True,
related_name="addresses",
limit_choices_to={'is_phone': True}
)
... more models with similar schema
在管理员中:
class ContactPhoneNumberInline(admin.StackedInline):
model = PhoneNumber
min_num = 0
max_num = 5
extra = 0
exclude = ["company"]
fields = (
("phone_type", "country", "phone_number"),
)
class ContactEmailAddressInline(admin.StackedInline):
model = EmailAddress
min_num = 0
max_num = 5
extra = 0
exclude = ["company"]
fields = (
("email_type", "email_address"),
)
.... more inlines w/ similar structure
@admin.register(Contact)
class ContactAdmin(admin.ModelAdmin):
fields = (
"company",
("name_first", "name_middle", "name_last",),
("name_salutation", "name_suffix", "title"),
)
inlines = [
ContactPhoneNumberInline,
ContactEmailAddressInline,
ContactDomainInline,
ContactAddressInline
]
编辑联系人时,操作是预期的。我可以向每种类型添加信息,并且这些类型将按照ForeignKeys中的指示进行过滤。
但是,UtilType的管理窗口具有布尔选择字段:is_address,is_phone,is_email,is_domain,因此用户必须选择此项才能正确过滤。我可以使用exclude方法隐藏这些字段。
但是我如何根据当前使用的内联自动填充正确的布尔值(= True)?
最好在模型中,在管理员中使用保存覆盖方法,还是有更好的方法来做到这一点?
我还没有在Django管理员中找到实现此目的的方法。如果有人知道这将是很好的信息。开发完成后,我将在前端处理该操作。我不确定管理员是否值得付出努力。