Polymorphic models like rails in Django? [closed]
In rails, I can declare a开发者_如何学JAVA model :polymorphic => true
and that would be enough to make the model be polymorphic.
But how can I create a polymorphic model in Django?
I know it's not simple as rails but I need a introduction for doing it in Django.
similar question here: Double Foreign Key in Django?
Answer is to use the ContentTypes framework in django to achieve polymorphic assocations.
There's a simple app called django-polymorphic-models that enables you to create polymorphic models with a basic downcast function. It works pretty simply, adds a field that stores the content type of the newly created object. Knowing the content type you can get the child model via object.*lowecase_model_name* (django represents inheritance internally via a OneToOneField
). If you use django-polymorphic-models a downcast
method on the model will give you the child model. Furthermore it adds some similar to methods to the queryset!
精彩评论