2012-09-26 31 views
2

我有一个模型,如下所示:如何通过文本进行的Django聚合函数

class Loves(models.Model): 
    poll = models.ForeignKey(Poll) 
    choice_text = models.CharField(max_length=200) 
    user_name = models.CharField(max_length=200) 

数据模型的样子:

调查choice_text用户

1麦克

1 b mike

1 c james

2个詹姆斯

2 B旋律

1 d迈克

我如何输出,看起来像一个列表:

用户的元组
迈克(1,)( 1,b),(1,d)
詹姆斯(1,C),(2,)
旋律(2,b)

谢谢。

回答

0
collection={} 
for l in Loves.objects.all(): 
    if l.user_name in collection: 
     collection[l.user_name].append((l.poll,l.choice_text)) 
    else: 
     collection[l.user_name]=[(l.poll,l.choice_text)] 
# and to turn it into a list just do 
results_list=list(collection) 
+0

我试过这个,它工作。谢谢。 –