With the child_object function defined in the parent model, you can get it's child object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Parent(models.Model):
child_class_names = (
'Child1',
'Child2',
'Child3',
)
def child_object(self):
for child_class_name in self.child_class_names:
try:
return self.__getattribute__(child_class_name.lower())
except eval(child_class_name).DoesNotExist:
pass
return self
class Child1(Parent):
pass
class Child2(Parent):
pass
class Child3(Parent):
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
This will is not a good solution since it will lead to lots of unnecessary load on the database (each self. will be a select query, possible with joins)
#
Well, this may be true; please tell me if you know a better solution or a workaround for this task, which I need often...
#
I need aswell but i dont think there is any at the moment. This has been discussed on the irc channel.
#
how about adding a field to Parent called object_name and override the save method on Parent to assign
I've just tried this in some of my code and it works for me
#
then in place of the child_object method in the example above you could use the following descriptor on Parent to get the child object:
#
Please login first before commenting.