开发者

Custom Chainable QuerySet

This is a piece of my code

from django.db import models
from django.db.models.query import QuerySet
from mptt.models import MPTTModel
from base.models import Content, OrderedContent


class ArgumentQuerySet(QuerySet):
    def statements_with_count(self, *args, **kwargs):
        from statement.models import Statement
        statements = Statement.objects.none()
        result = self
        for node in result:
            statements_node = Statement.objects.filter( arguments__in = node.get_descendants(include_self = True), *args, **kwargs ).distinct()
            statements |= statements_node
            setattr(node, 'count', statements_node.count())
        statements = statements.distinct()
        setattr(result, 'statements', statements)
        setattr(result, 'count',开发者_JAVA技巧 statements.count())
        return result


class ArgumentManager(models.Manager):
    def get_query_set(self):
        return ArgumentQuerySet(self.model)


class Argument(MPTTModel, OrderedContent):
    parent = models.ForeignKey('self', null=True, blank=True)
    objects = ArgumentManager()

    class MPTTMeta:
        parent_attr = 'parent'
        order_insertion_by = ['weight', 'title', ]

    def __unicode__(self):
        return self.title

The following commands gives me the attended result

a = Argument.objects.filter( title__icontains = 'function' )
b = a.statements_with_count()

Otherwise, the following commands doesn't work

c = Argument.objects.get( id = 514 )
d = c.get_children()
e = d.statements_with_count()

How can i fix this problem?


MPTT uses the TreeManager instance for get_children which returns a models.query.Queryset, not your custom subclass of it. You chould do somethling like:

argument = Argument.objects.get(id = 514)
children_ids = [a.pk for a in argument.get_children()]
result = Argument.objects.filter(pk__in=children_ids).statements_with_count()

Note that your statements_with_count method is not very performant, as it will cause one additional database count for each object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜