擅长:python、mysql、java
<p>您可以获得所有唯一的姓氏:</p>
<pre><code>from django.db.models import Count
...
last_names = Person.objects.values('last_name').annotate(Count('last_name')) # This will return all the unique last_names
values = dict( ((last_name['last_name'], Person.objects.all().filter(last_name = last_name['last_name'])) for last_name in last_names if last_name['last_name__count']) )
# This will create a dictionary where the keys are all the unique names and the values are querysect of all the values that have that lastname
</code></pre>
<p>丹尼尔罗斯曼是对的,这是相当低效的,所以这里有一个调整版本。。。</p>
<pre><code>from collections import defaultdict
values = defaultdict(list)
_ = map(lambda person: values[person.last_name].append(person), Person.objects.all())
</code></pre>
<p>注意<code>_ = ...</code>是这样的,所以我们不会在终端上打印所有的<code>None</code>;)</p>