这是我的一段代码
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', 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
以下命令为我提供了参加结果
a = Argument.objects.filter( title__icontains = 'function' )
b = a.statements_with_count()
否则,以下命令不起作用
c = Argument.objects.get( id = 514 )
d = c.get_children()
e = d.statements_with_count()
我该如何解决这个问题?
答案 0 :(得分:0)
MPTT使用TreeManager
get_children
实例返回models.query.Queryset
,而不是您的自定义子类。你可以做一些像:
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()
请注意,您的statements_with_count
方法效率不高,因为它会为每个对象带来一个额外的数据库计数。