我的愿望是有一个通用的位置模型,然后让需要位置的各种更高级别的模型引用它。
我想在管理员中向我的用户展示一个多部分表单(内联),允许他们输入发布者和建筑物的更高级别信息,以及每个部分的位置信息。内联系统似乎不想以这种方式工作。
显然,我做错了什么,因为这对我来说似乎是一个非常标准的问题。我的架构设计很无聊吗?
我在愚蠢地使用内联系统吗?我不想为每个上层对象做 Location 的子类,因为我想以不同的方式操作位置,而与拥有它们的任何高级对象无关(邮件列表或地理查找)
models.py:
...
class Location(models.Model):
"""
A geographical address
"""
# Standard Location stuff
address_line1 = models.CharField("Address line 1", max_length = 45, null=True, blank=True)
...
class Publisher(models.Model):
"""
Contains Publisher information for publishers of yearbooks. Replaces Institution from 1.x
"""
name = models.CharField(max_length=100, null=False, help_text="Name of publisher, e.g. University of Kansas")
groups = models.ManyToManyField(Group, help_text="Select groups that this publisher owns. Usually just one, but multiple groups are possible.")
is_active = models.BooleanField(help_text="Check this box to enable this publisher.")
location = models.OneToOneField(Location)
...
class Building(models.Model):
"""
Contains Building Information
"""
name = models.CharField(max_length=100, null=False, help_text="Name of building, e.g. Physical Sciences")
is_active = models.BooleanField(help_text="Check this box to enable this building.")
location = models.OneToOneField(Location)
...
admin.py:
...
class LocationInline(generic.GenericStackedInline):
model = Location
max_num = 1
extra = 1
class PublisherAdmin(admin.ModelAdmin):
model = Publisher
inlines = [ LocationInline,
]
class BuildingAdmin(admin.ModelAdmin):
model = Building
inlines = [ LocationInline,
]
admin.site.register(Publisher, PublisherAdmin)
admin.site.register(Building, BuildingAdmin)
我可以通过将其添加到 Location 模型来强制内联加载和呈现:
# Support reverse lookup for admin
object_id = models.PositiveIntegerField()
content_type = models.ForeignKey(ContentType)
of = generic.GenericForeignKey('content_type', 'object_id' )
但是当我这样做时,即使我确实得到了一个内联对象,并且可以编辑它,这种关系对我来说似乎是倒退的,Location 将一个 id 存储到创建它的对象中。
欢迎任何帮助,无论是推荐的架构更改以使一切都完美地工作(因为 Django 非常擅长),或者是使看起来向后的东西有意义的技巧。