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

Comments

daevaorn (on November 14, 2008):
<p>May be?</p> <pre>self.content_type = ContentType.objects.get_for_model(self.__class__) </pre>

#

rix (on November 14, 2008):
<p>The get_for_model method accepts an instance also, I think it'll work in both cases.</p>

#

rix (on November 18, 2008):
<p>You're right carljm, the code can be improved with your fix.</p> <p>In my use, a Place is never created by itself, only through child classes, so I'd never got affected.</p> <p>I'll fix the code, thanks for the tip.</p>

#

Please login first before commenting.