लेखन के समय, जैंगो नवीनतम संस्करण 1.2
था लेकिन यह काम करने के लिए कुछ अतिरिक्त तत्वों की जरूरत है।
आपको एक कस्टम मॉडल असाइन करने की आवश्यकता है। प्रत्येक पशु मॉडल के लिए प्रबंधक ऑब्जेक्ट जो अपनी कस्टम क्वेरीरी ऑब्जेक्ट को कॉल करेगा।
असल में, बजाय यदि आइटम के मॉडल Animal
है या नहीं की जाँच करने के Animal
उदाहरणों (यह आप क्या मिलता है), SubclassingQuerySet
कॉल as_leaf_class()
विधि लौटने की - अगर ऐसा है, तो बस इसे वापस, नहीं तो अपने मॉडल के संदर्भ में खोज करें। बस।
#models.py
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.db.models.query import QuerySet
class SubclassingQuerySet(QuerySet):
def __getitem__(self, k):
result = super(SubclassingQuerySet, self).__getitem__(k)
if isinstance(result, models.Model):
return result.as_leaf_class()
return result
def __iter__(self):
for item in super(SubclassingQuerySet, self).__iter__():
yield item.as_leaf_class()
class AnimalManager(models.Manager):
def get_query_set(self): # Use get_queryset for Django >= 1.6
return SubclassingQuerySet(self.model)
class Animal(models.Model):
name = models.CharField(max_length=100)
content_type = models.ForeignKey(ContentType, editable=False, null=True)
objects = AnimalManager()
def __unicode__(self):
return "Animal: %s" % (self.name)
def save(self, *args, **kwargs):
if not self.content_type:
self.content_type = ContentType.objects.get_for_model(self.__class__)
super(Animal, self).save(*args, **kwargs)
def as_leaf_class(self):
content_type = self.content_type
model = content_type.model_class()
if model == Animal:
return self
return model.objects.get(id=self.id)
class Sheep(Animal):
wool = models.IntegerField()
objects = AnimalManager()
def __unicode__(self):
return 'Sheep: %s' % (self.name)
परीक्षण:
>>> from animals.models import *
>>> Animal.objects.all()
[<Sheep: Sheep: White sheep>, <Animal: Animal: Dog>]
>>> s, d = Animal.objects.all()
>>> str(s)
'Sheep: White sheep'
>>> str(d)
'Animal: Dog'
>>>
[django-polymorphic] (https://github.com/chrisglass/django_polymorphic) देखें, जो इस उपयोग के मामले के लिए डिज़ाइन किया गया है। यह तब भी काम करता है जब मॉडल विदेशीकी, ManyToManyFields, आदि के माध्यम से लाया जाता है .. – vdboor
ऐसा मत करो! : पी नीचे अपना ले देखें: http://stackoverflow.com/a/20353347/539490 – AJP