Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model inheritance, overriding fields

I am reading the book Python Web Development with Django and I found this example in the book:

 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'})

It seems like it is not working:

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

I am using Django 1.5.3 and the book is for Django 1.0.

Why it is not possible to override fields when inherit in Django? Was it possible in Django 1.0, or it is an error in the book?

like image 551
sergiuz Avatar asked Dec 19 '22 23:12

sergiuz


1 Answers

Don't think this has been allowed in django, not even 1.0.

From 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.

This still holds for the latest version of django.

like image 121
Rohan Avatar answered Dec 22 '22 12:12

Rohan