2013-09-26 173 views
3

我讀這本書的Python Web開發Django和我發現這書上的例子:的Django模型繼承,覆蓋領域

class Book(models.Model): 
      title = models.CharField(max_length=100) 
      genre = models.CharField(max_length=100) 
      num_pages = models.IntegerField() 
      authors = models.ManyToManyField(Author) 

      def __unicode__(self): 
       return self.title 

    class SmithBook(Book): 
     authors = models.ManyToManyField(Author, limit_choices_to={'name__endswith': 'Smith'}) 

現在看來似乎是行不通的:

FieldError: Local field 'authors' in class 'SmithBook' clashes with field of similar name from base class 'Book'

我使用的是Django 1.5.3,本書是針對Django 1.0的。

爲什麼在繼承Django時無法覆蓋字段?在Django 1.0中可能會出現這種情況嗎?或者這是書中的錯誤?

回答

10

不要認爲這已被允許在django,甚至不是1.0。

Field name 「hiding」 is not permitted - django 1.0

In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this is not permitted for attributes that are Field instances (at least, not at the moment). If a base class has a field called author, you cannot create another model field called author in any class that inherits from that base class.

這仍然適用於Django的最新版本。