Django queryset相对于其他列获取不同的列值 [英] Django queryset get distinct column values with respect to other column
问题描述
我正在使用django orm,并且尝试获取一列的所有值,但前提是只有不同的列对此具有唯一性。很难解释,因此这里是一个示例:
I am using django orm and I am trying to get all the values of a column, but only if a different column is unique with respect to it. Its hard to explain, so here is an example:
q | a | 1
w | s | 2
e | a | 3
q | a | 4
w | s | 5
e | a | 6
我想获取第2列中的所有值,但是如果它们也具有相同的值第1列中的值不能重复。因此,在这种情况下,我想获得[a,s,a]。 (第3列仅用于说明为什么这些重复项没有首先合并)。
I would like to get all the values that are in column 2 but if they also have the same value in column 1 don't take duplicates. So in this case I want to get [a,s,a]. (column 3 only serves to show why these duplicates don't get merged in the first place).
我尝试过的操作:
我尝试根据第1列和第2列的值进行分组并取其不同的值,因此最终得到:
q | a
w | s --->实际上为[(q,a),(w,s),(e,a)]
e | a
,其代码为: queryset.values(col1,col2).distinct()
但我只想要第二列,所以我然后添加 .values(col2)
。这样做的问题是,第二个值
和第一个值的结果都不同,所以我得到的不是[a,s,a],而是,s]。
我也尝试使用 .defer()
,所以 queryset.values(col1,col2).distinct( ).defer(col1)
,但显然在使用 .values()<后,您不能再使用
.defer()
/ code>。
What I tried:
I tried grouping by values of columns 1 and 2 and taking the distinct value of it, thus I would end up with:
q | a
w | s ---> which is actually given as [(q,a),(w,s),(e,a)]
e | a
with the code: queryset.values(col1,col2).distinct()
but I only want the second column so I then added .values(col2)
. The problem with that is the distinct gets applied to the results of the second values
as well as the first, so instead of getting [a,s,a] I get [a,s].
I also tried using .defer()
so queryset.values(col1,col2).distinct().defer(col1)
but apparently you can't use .defer()
after using .values()
.
我无法在网上找到解决方案,而且暂时无处可寻,任何帮助将不胜感激!
I can't find a solution to this online and am getting nowhere for a while now, any help would be greatly appreciated!
推荐答案
如果您使用PostgreSQL作为数据库,请尝试以下操作:
If you are using PostgreSQL as your database, try this:
queryset.order_by('col1', 'col2').distinct('col1', 'col2').values('col2')
我没有机会对其进行测试,但是它应该在 col1 $ c $的组合中找到结果c>和
col2
是不同的,并返回 col2
值。
I haven't had a chance to test it, but it should find results where the combination of col1
and col2
are distinct, and return the col2
values.
这篇关于Django queryset相对于其他列获取不同的列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!