2013-09-26 4 views
3

Я читаю книгу Python Веб-разработка с 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

Не думайте, что это разрешено в джанго, даже не 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.

Это все еще имеет место для последней версии Джанго.

Смежные вопросы