Django Multiple inheritance with different tables

Viewed 2209

I tried to create some models. I actually looked at some examples but most of them don't work. Example:

class Piece(models.Model):
    name =  models.CharField(max_length=100)    
    class Meta:
        abstract = True

class Article(Piece):
    pass        

class Book(Piece):
    pass

class Monday(Book, Article):
    pass    
class Tuesday(Book, Article):
    pass

So my goal is to get the value with something like this -> Monday.Article.name. I want to have different tables for every weekday, containing the article's name. This is the error I get:

ERRORS:
Testing.Monday: (models.E005) The field 'id' from parent model 'Testing.book' clashes with the field 'id' from parent model 'Testing.article'.
Testing.Monday: (models.E005) The field 'name' from parent model 'Testing.book' clashes with the field 'name' from parent model 'Testing.article'.
Testing.Tuesday: (models.E005) The field 'id' from parent model 'Testing.book' clashes with the field 'id' from parent model 'Testing.article'.
Testing.Tuesday: (models.E005) The field 'name' from parent model 'Testing.book' clashes with the field 'name' from parent model 'Testing.article'.

It looks like my Article and Book are using the same name. How does this work?

EDIT: Using this :

class Article(Piece):
   article_id = models.AutoField(primary_key=True)

class Book(Piece):
   book_id = models.AutoField(primary_key=True)

Will result in this error:

Testing.Monday: (models.E005) The field 'piece_ptr' from parent model 
'Testing.book' clashes with the field 'piece_ptr' from parent model 
'Testing.article'.

The only solution is this: article_to_piece = models.OneToOneField(Piece, parent_link=True)But this will not generate a linking between the days and a book/article. I can only add a name to the day.

2 Answers

You should try calling init on subclasses, like:

class Monday(Book, Article):
    id = models.AutoField(primary_key=True)
    name= models.CharField(max_length=100)

    def __init__(self, *args, **kwargs):
        return super().__init__(*args, **kwargs)


class OtherDay(Book, Article):
    book_id = models.AutoField(primary_key=True)
    book_name= models.CharField(max_length=100)

    def __init__(self, *args, **kwargs):
        return super().__init__(*args, **kwargs)

This is because, as a Python class, the super() method will call the superclasses definition only one time, while the simple inheritance would call ini() for each superclass.

Related