根据特定字段从Django中的数据库获取不同的行 [英] Getting distinct rows based on a certain field from a database in Django
问题描述
我需要在Django中构造一个查询,我想知道这是否有可能(它确实很明显,但我很想念...)。
I need to construct a query in Django, and I'm wondering if this is somehow possible (it may be really obvious but I'm missing it...).
我有一个普通查询 Model.objects.filter(x = True)[:5]
,它可以返回如下结果:
I have a normal query Model.objects.filter(x=True)[:5]
which can return results like this:
FirstName LastName Country
Bob Jones UK
Bill Thompson UK
David Smith USA
我只需要抓取根据而不同的行Country
字段,例如 Model.objects.filter(x = True).distinct('Country')[:5]
I need to only grab rows which are distinct based on the Country
field, something like Model.objects.filter(x=True).distinct('Country')[:5]
would be ideal but that's not possible with Django.
我希望查询最终获取的行是:
The rows I want the query to grab ultimately are:
FirstName LastName Country
Bob Jones UK
David Smith USA
I还需要查询使用与模型的Meta类中设置的顺序相同的顺序(即我无法以任何方式取消排序。)
I also need the query to use the same ordering as set in the model's Meta class (ie. I can't override the ordering in any way).
我将如何去做呢?
非常感谢。
推荐答案
我还没有对此进行测试,但是在我看来,尽管订购了dict,但字典还是可以胜任的可能会关闭:
I haven't tested this, but it seems to me a dict should do the job, although ordering could be off then:
d = {}
for x in Model.objects.all():
d[x.country] = x
records_with_distinct_countries = d.values()
这篇关于根据特定字段从Django中的数据库获取不同的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!