擅长:python、mysql、java
<p>Django 1.1确实支持像count这样的聚合方法。你可以找到<a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/" rel="noreferrer">the full documentation here</a>。</p>
<p>要回答您的问题,您可以使用以下内容:</p>
<pre><code>from django.db.models import Count
q = Player.objects.annotate(Count('games'))
print q[0]
print q[0].games__count
</code></pre>
<p>这将需要根据您的实际模型稍加调整。</p>
<p>编辑:以上代码片段基于每个对象生成聚合。如果希望在模型中的特定字段上进行聚合,可以使用<code>values</code>方法:</p>
<pre><code>from django.db.models import Count
q = Player.objects.values('playertype').annotate(Count('games')).order_by()
print q[0]
print q[0].games__count
</code></pre>
<p>需要<code>order_by()</code>,因为即使未显式传递给<code>values()</code>,也会自动选择默认顺序中的字段。此对<code>order_by()</code>的调用清除任何排序,并使查询按预期行为。</p>
<p>此外,如果要计算用于分组的字段(相当于<code>COUNT(*)</code>),可以使用:</p>
<pre><code>from django.db.models import Count
q = Player.objects.values('playertype').annotate(Count('playertype')).order_by()
print q[0]
print q[0].playertype__count
</code></pre>