如何在django中使用group by许多文件

时间:2015-01-15 08:23:25

标签: django sql-order-by

我有一个三个领域的模型:电子邮件,电话,邮政编码。如果有相同的字段,我们只需要记录第一条记录 例如:

field     email         phone    postal_code
record1   a@gmail.com   123      12
record2   b@gmail.com   321      12
record3   c@gmail.com   123      21

对于postal_code:我们可以获取record1和record3,然后通过电话(是123),结果是record1。最后我可以得到记录。

1 个答案:

答案 0 :(得分:0)

让我们将您的模型名称设为Record,您可以这样做:

Record.objects.all()  # This return all record objects

Record.objects.all().order_by('phone')  # Ascendent order by
Record.objects.all().order_by('-phone')  # Descendent order by

Record.objects.filter(phone=123)  # This should return record1 and record3

# This should return record1 and record3 ordered by postal_code ascendent
Record.objects.filter(phone=123).order_by('postal_code')  

# This should return record1 and record3 ordered by postal_code descendent
Record.objects.filter(phone=123).order_by('-postal_code')  

# This return a list of tuples [('record1', 12), ...]
Record.objects.filter(postal_code=12).values_list('name','postal_code')

# This return a list of dictionaries [{'name':'record1', 'postal_code':12}, ...]
Record.objects.filter(postal_code=12).values('name','postal_code)