Login

Child aware model inheritance

Author:
rix
Posted:
November 14, 2008
Language:
Python
Version:
1.0
Tags:
model inheritance child content-type
Score:
2 (after 2 ratings)

Base models aren't aware of its inherited models, here is a quick solution to access child models from the base model.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Place(models.Model):
    name = models.CharField('name')
    content_type = models.ForeignKey(ContentType)
    # Child model
    child = generic.GenericForeignKey(fk_field='id')
    
    def save(self, **kwargs):
        if not self.pk:
            self.content_type = ContentType.objects.get_for_model(self)
        super(Place, self).save(**kwargs)
    
class Restaurant(Place):
    pass

More like this

  1. Get child model by Hangya 7 years ago
  2. update primary key (cascade to child tables and inherited models) by variant 2 years ago
  3. Custom optional abstract base attributes by tie 6 years, 11 months ago
  4. Model inheritance with content type and inheritance-aware manager by dan90 6 years, 8 months ago
  5. Model with random ID by jobs@flowgram.com 6 years, 11 months ago

Comments

daevaorn (on November 14, 2008):

May be?

self.content_type = ContentType.objects.get_for_model(self.__class__)

#

rix (on November 14, 2008):

The get_for_model method accepts an instance also, I think it'll work in both cases.

#

rix (on November 18, 2008):

You're right carljm, the code can be improved with your fix.

In my use, a Place is never created by itself, only through child classes, so I'd never got affected.

I'll fix the code, thanks for the tip.

#

Please login first before commenting.