我使用Django 1.10。我有以下模型结构:
class GenericPage(models.Model):
"""Abstract page, other pages inherit from it."""
book = models.ForeignKey('Book', on_delete=models.CASCADE)
class Meta:
abstract = True
class GenericColorPage(models.Model):
"""Abstract page that is sketchable and colorable, other pages inherit from it."""
sketched = models.BooleanField(default=False)
colored = models.BooleanField(default=False)
class Meta:
abstract = True
class GenericBookPage(GenericColorPage):
"""A normal book page, with a number. Needs to be storyboarded and edited."""
###
#various additional fields
###
class Meta:
# unique_together = (('page_number', 'book'),) # impedes movement of pages
ordering = ('-book', '-page_number',)
abstract = True
objects = BookPageManager() # the manager for book pages
class BookPage(GenericBookPage):
"""Just a regular book page with text (that needs to be proofread)"""
proofread = models.BooleanField(default=False)
此外,摘自管理员:
class BookPageAdmin(admin.ModelAdmin):
# fields NOT to show in Edit Page.
list_display = ('__str__', 'page_name', 'sketched', 'colored', 'edited', 'proofread',)
list_filter = ('book',)
readonly_fields = ('page_number',) # valid page number is assigned via overridden save() in model
actions = ['delete_selected',]
我尝试./manage.py makemigrations
但是如果抛出以下错误:
<class 'progress.admin.BookPageAdmin'>: (admin.E116) The value of 'list_filter[0]' refers to 'book', which does not refer to a Field.
progress.BookPage: (models.E015) 'ordering' refers to the non-existent field 'book'.
过去,当我没有使用摘要并将所有内容都放入BookPage
模型时,一切正常。但似乎Meta和Admin没有看到父类中的字段。我错过了什么吗?有没有办法让他们从抽象的父母那里读取字段?
答案 0 :(得分:2)
过去,当我没有使用摘要并将所有内容都放入BookPage模型时,一切都运行良好
当然它运行正常,因为你把所有内容放在BookPage
里面而不是abstract class,这意味着将创建表格(以及字段)。
但似乎Meta和Admin没有看到父类中的字段。我错过了什么吗?
您错过了这样一个事实:您的模型都没有从GenericPage
抽象模型继承。因此,永远不会创建book
字段。
有没有办法让他们从抽象父母那里读取字段?
您必须创建/修改从抽象模型继承的模型。也许,这样做:
class GenericBookPage(GenericColorPage, GenericPage):
允许您继承GenericColorPage
和GenericPage
字段。当我说继承时,我的意思是当migrate
命令运行以实际创建数据库表和相关列(模型字段)时。