Getting distinct rows based on a certain field from a database in Django

十年热恋 提交于 2019-12-04 15:10:45

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()
countries = [f.country in Model.objects.all()]

for c in countries:
    try:
        print Model.objects.filter(country=c)
    except Model.DoesNotExist:
        pass 

I think that @skrobul is on the right track, but a little bit off.

I don't think you'll be able to do this with a single query, because the distinct() method adds the SELECT DISTINCT modifier to the query, which acts on the entire row. You'll likely have to create a list of countries and then return limited QuerySets based on iterating that list.

Something like this:

maxrows = 5
countries = set([x.country for x in Model.objects.all()])
rows = []
count = 0
for c in countries:
    if count >= maxrows:
        break

    try:
        rows.append(Model.objects.filter(country=c)[0])
    except Model.DoesNotExist:
        pass

    count += 1

This is a very generic example, but it gives the intended result.

Can you post the raw SQL that returns what you want from the source database? I have a hunch that the actual problem here is the query/data structure...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!