5

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?

stf
  • 591
  • 1
  • 4
  • 19
  • Oddly enough, `models.AutoField(primary_key=True)` works according to the docs. – dmg Jan 14 '15 at 12:23
  • @dmg I guess you're referring to the docs on [multiple inheritance](https://docs.djangoproject.com/en/1.7/topics/db/models/#multiple-inheritance). The trick there is that an `AutoField` named `id` is implicitly added to `Piece`. Child models inherit this field, so they already have a primary key. This prevents a new implicit `id` field from being added -> no name clash. That doesn't mean in anyway that you can override a parent field. – knbk Jan 14 '15 at 13:40

1 Answers1

1

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. :)

MiniGunnR
  • 5,590
  • 8
  • 42
  • 66