django-polymodels

Polymorphic models implementation for Django
Download

django-polymodels Ranking & Summary

Advertisement

  • Rating:
  • License:
  • MIT/X Consortium Lic...
  • Price:
  • FREE
  • Publisher Name:
  • Simon Charette
  • Publisher web site:
  • https://github.com/charettes/

django-polymodels Tags


django-polymodels Description

django-polymodels is a Django app that provides a simple way to retrieve models type casted to their original ContentType.Installationpip install polymodelsMake sure ``'django.contrib.contenttypes'`` and ``'polymodels'`` are in your `INSTALLED_APPS`:: INSTALLED_APPS += ('django.contrib.contenttypes', 'polymodels')UsageYou subclass ``PolymorphicModel`` which is an abstract model class... _models::: from django.db import models from polymodels.models import PolymorphicModel class Animal(PolymorphicModel): name = models.CharField(max_length=255) def __unicode__(self): return self.name class Mammal(Animal): pass class Dog(Mammal): pass class Reptile(Animal): pass class Snake(Reptile): class Meta: proxy = TrueObjects are created the same way as usual and their associated ``ContentType`` is saved automatically.>>> animal = Animal.objects.create(name='animal')>>> mammal = Mammal.objects.create(name='mammal')>>> reptile = Reptile.objects.create(name='reptile')>>> snake = Snake.objects.create(name='snake')To retreive *type casted* instances from the ``Animal.objects`` manager you just have to use the ``select_subclasses`` method:>>> Animal.objects.select_subclasses()You can also retreive a subset of the subclasses by passing them as arguments to ``select_subclass``:>>> Animal.objects.select_subclasses(Reptile)Or directly from subclasses managers:>>> Reptile.objects.select_subclasses(Snake)Note that you can also retreive original results by the ``select_subclasses`` call.>>> Animal.objects.select_subclasses()Each instance of ``PolymorphicModel`` has a ``type_cast`` method that knows how to convert itself to the correct ``ContentType``.>>> animal_snake = Animal.objects.get(pk=snake.pk)< Animal: snake >>>> animal_snake.type_cast()< Snake: snake >>>> animal_snake.type_cast(Reptile)< Reptile: snake >If the ``PolymorphicModel.content_type`` fields conflicts with one of your existing fields you just have to subclass ``polymodels.models.BasePolymorphicModel`` instead. Just don't forget to indicates which field it should use instead by defining a ``content_type_field_name'`` attribute on you model. This field should be a ``ForeignKey`` to ``ContentType``:: from django.contrib.contenttypes.models import ContentType from django.db import models from polymodels.models import BasePolymorphicModel class MyModel(BasePolymorphicModel): content_type_field_name = 'polymorphic_ct' polymorphic_ct = models.ForeignKey(ContentType)Product's homepage


django-polymodels Related Software