Re: Get child model class
Ok this solution worked for me :):)
{{{
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()
else :
return result
def __iter__(self):
for item in super(SubclassingQuerySet, self).__iter__():
yield item.as_leaf_class()
class CFManager(models.Manager):
def get_query_set(self):
return SubclassingQuerySet(self.model)
class CF(models.Model):
type = models.CharField(max_length = 40)
content_type =
models.ForeignKey(ContentType,editable=False,null=True)
objects = CFManager()
def save(self, *args, **kwargs):
if(not self.content_type):
self.content_type =
ContentType.objects.get_for_model(self.__class__)
super(CF, self).save(*args, **kwargs)
def as_leaf_class(self):
content_type = self.content_type
model = content_type.model_class()
if (model == CF):
return self
return model.objects.get(id=self.id)
class CFT(CF):
data = models.CharField(max_length=20)
objects = CFManager()
class CFI(CF):
data = models.IntegerField()
objects = CFManager()
class Doc(models.Model):
name = models.CharField(max_length = 40)
cf = models.ManyToManyField(CF, null = True)
}}}
now when I do:
In [12]: doc.cf.all()
Out[12]: [<CFT: CFT object>, <CFI: CFI object>]
Thanks for all the suggestions and help.
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home