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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
May be?
#
The
get_for_model
method accepts an instance also, I think it'll work in both cases.#
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.