【问题标题】:Admin and Meta don't see the fields of parent abstract classesAdmin 和 Meta 看不到父抽象类的字段
【发布时间】:2017-04-20 06:11:40
【问题描述】:

我使用 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 看不到父类中的字段。我错过了什么吗?有没有办法让他们从抽象父母那里读取字段?

【问题讨论】:

    标签: django python-3.x inheritance django-models


    【解决方案1】:

    过去,当我不使用摘要并将所有内容放入 BookPage 模型时,一切正常

    当然它工作得很好,因为你把所有东西都放在BookPage 里面,这不是abstract class,这意味着将创建表(以及字段)。

    但似乎 Meta 和 Admin 看不到父类中的字段。我错过了什么吗?

    您错过了没有一个模型继承自 GenericPage 抽象模型的事实。因此,永远不会创建 book 字段。

    有没有办法让他们从抽象父母那里读取字段?

    您必须创建/修改从抽象模型继承的模型。也许,这样做:

    class GenericBookPage(GenericColorPage, GenericPage):
    

    这允许您继承GenericColorPageGenericPage 字段。当我说继承时,我的意思是当 migrate 命令运行以实际创建数据库表和相关列(模型字段)时。

    【讨论】:

    • 哦,男孩,我在这里犯了一个错误。它应该是GenericColorPage(GenericPage):!我差点以为 Django 无法遍历摘要树,但一开始就没有树。感谢您指出!
    猜你喜欢
    • 2016-09-11
    • 2014-01-02
    • 1970-01-01
    • 2013-02-05
    • 2016-04-15
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    • 2020-09-14
    相关资源
    最近更新 更多