这是我的一段代码
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()
如何解决这个问题?
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
方法性能不是很好,因为它将为每个对象导致一个额外的数据库计数。