2013-09-26 172 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的最新版本。