根据Django上的列检索不同的记录 [英] Retrieving distinct records based on a column on Django

查看:137
本文介绍了根据Django上的列检索不同的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检索以下表的记录列表,其名称不同:

I need to retrieve a list of records for the following table with distinct values in regards to name:

Class C:

name                value
A ------------------ 10
A ------------------ 20
A ------------------ 20
B ------------------ 50
C ------------------ 20
D ------------------ 10
B ------------------ 10
A ------------------ 30

我需要摆脱名称的所有重复值,只显示以下内容: / p>

I need to get rid of all the duplicate values for name and only show the following:

name                value
A ------------------ 30
B ------------------ 10
C ------------------ 20
D ------------------ 10

你可以看到,它几乎看起来像一个python集。我可以使用Python生成集合,但我想知道Django的ORM是否具有此功能。

As you can see, it almost looks like a python set. I can probably generate the set using Python, but I'm wondering if Django's ORM has this feature.

我尝试使用distinct,但它不接受任何参数来指定哪个列必须具有不同的值。任何想法如何让这个查询工作?

I tried using distinct, but it doesn't accept any argument to specify which column has to have distinct values. Any idea how to get this query working?

推荐答案

.distinct()是工具,但这里是我必须使用的语法:

.distinct() is the tool, but here's the syntax I had to use :

Model.objects.values_list('name', flat=True).distinct()

这样你只能得到一个列表[A,B,C,D ]的值,而不是它们的对象。

This way you only get a list [A,B,C,D] of values, not the objects themseleves.

这篇关于根据Django上的列检索不同的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆