Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Field diamond pattern in multiple abstract model inheritance in Python/Django

I am having the following model class hierarchy:

from django.db import models

class Entity(models.Model):
    createTS = models.DateTimeField(auto_now=False, auto_now_add=True)

    class Meta:
        abstract = True

class Car(Entity):
    pass

    class Meta:
        abstract = True

class Boat(Entity):
    pass

class Amphibious(Boat,Car):
    pass

Unfortunately, this does not work with Django:

shop.Amphibious.createTS: (models.E006) The field 'createTS' clashes with the field 'createTS' from model 'shop.boat'.

Even if I declare Boat abstract, it doesn't help:

shop.Amphibious.createTS: (models.E006) The field 'createTS' clashes with the field 'createTS' from model 'shop.amphibious'.

Is it possible to have a model class hierarchy with multiple inheritance and a common base class (models.Model subclass) that declares some fields?

like image 473
stf Avatar asked Nov 22 '22 04:11

stf


1 Answers

Use this and see if it helps. If you are trying to include the timestamp to the models then just create a base model which includes only the timestamp.

from django.db import models

class Base(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Boat(Base):
    boat_fields_here = models.OnlyBoatFields()

class Amphibious(Boat):
    # The boat fields will already be added so now just add
    # the car fields and that will make this model Amphibious
    car_fields_here = models.OnlyCarFields()

I hope this helps. I see that it has been 5 months since you posted this question. If you have already found a better solution then please share it with us, will help us a lot for learning. :)

like image 155
MiniGunnR Avatar answered Dec 19 '22 10:12

MiniGunnR