2017-04-20 20 views
0

我使用Django 1.10。我有以下的模型結構:Admin和Meta沒有看到父抽象類的字段

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沒有看到父類中的字段。我錯過了什麼嗎?有沒有辦法讓他們閱讀抽象父母的領域?

回答

2

在過去,當我沒有使用摘要,只是把一切都變成BookPage模式,它都能正常運作

當然它工作得很好,因爲你把裏面的東西BookPage這不是abstract class這意味着將創建表(以及字段)。

但似乎元和管理員看不到父類中的字段。我錯過了什麼嗎?

您錯過了您的模型沒有從GenericPage抽象模型繼承的事實。因此,book字段永遠不會被創建。

有沒有辦法讓他們閱讀抽象的父母領域?

您必須創建/修改從抽象模型繼承的模型。也許,這樣做:

class GenericBookPage(GenericColorPage, GenericPage): 

,它允許你同時繼承GenericColorPageGenericPage領域。當我說繼承時,我的意思是當migrate命令運行時實際創建數據庫表和相關列(模型字段)。

+0

哦,男孩,我在那裏犯了一個錯誤。它應該是'GenericColorPage(GenericPage):'而不是!我幾乎認爲Django無法遍歷摘要樹,但首先沒有樹。感謝您指出! – Highstaker