Login

Child aware model inheritance

Author:
rix
Posted:
November 14, 2008
Language:
Python
Version:
1.0
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 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.