I use a snippet in http://www.djangosnippets.org/snippets/1034/ for my
Model inheritance. It works fine at the first.However, after I delete
some elements in database, the code works wrong.
As I debug, I found that the problem resides in the method:
as_leaf_class.
In the following code:
    def as_leaf_class(self):
        content_type = self.content_type
        model = content_type.model_class()
 (1*)       if(model == Contact):
            return self
(2*)        return model.objects.get(id=self.id)
when query a deleted object, line (1*) will be False, So it tries to
run line (2*) which raise an exception from get()
Anyone could give a solution for this?


The snippets I use is following:
Model inheritance with content type and inheritance-aware manager
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 MealManager(models.Manager):
    def get_query_set(self):
        return SubclassingQuerySet(self.model)

class Meal (models.Model) :
    name = models.TextField(max_length=100)
    content_type = models.ForeignKey
(ContentType,editable=False,null=True)
    objects = MealManager()

    def save(self, *args, **kwargs):
        if(not self.content_type):
            self.content_type = ContentType.objects.get_for_model
(self.__class__)
            super(Meal, self).save(*args, **kwargs)

    def as_leaf_class(self):
        content_type = self.content_type
        model = content_type.model_class()
        if (model == Meal):
            return self
        return model.objects.get(id=self.id)

class Salad (Meal) :
    too_leafy = models.BooleanField(default=False)
    objects = MealManager()

--~--~---------~--~----~------------~-------~--~----~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to