2015-09-26 48 views
-1
from django.db import models 
from mezzanine.pages.models import Page 

# The members of Page will be inherited by the Author model, such 
# as title, slug, etc. For authors we can use the title field to 
# store the author's name. For our model definition, we just add 
# any extra fields that aren't part of the Page model, in this 
# case, date of birth. 

class Author(Page): 
    dob = models.DateField("Date of birth") 

class Book(models.Model): 
    author = models.ForeignKey("Author") 
    cover = models.ImageField(upload_to="authors") 

因此,Book也繼承了Page的屬性嗎?那麼這意味着頁面的任何屬性或方法都可以通過上面的代碼訪問?Python Django夾層模型導入

回答

2

如果要擴展模型,最好使用外鍵關係。您可以與包含字段的模型建立一對一的關係以獲取更多信息。例如:

class Author(models.Model): 
    page = models.OneToOneField(Page) 
    dob = models.DateField("Date of birth") 

你可以使用Django的標準相關示範公約訪問相關信息:

a = Author.objects.get(...) 
name = a.page.title # author's name is stored in Page.title field