1

How would I do the following query in django:

Asset.objects.all().distinct('checksum') # get all distinct checksum items

The equivalent in SQL would be:

SELECT * FROM asset GROUP BY checksum

Note that I need all fields here, so I cannot do something like Asset.objects.values_list('checksum').distinct(). How would I do this?

David542
  • 104,438
  • 178
  • 489
  • 842
  • Not sure exactly what you're asking for here. Can you provide an example dataset, and your desired result? – Joseph Oct 17 '14 at 07:11

1 Answers1

1

Do you want to get the first item of every checksum?

items = Asset.objects.all()
items.query.group_by = ['checksum']
print items
[<Asset: ...]
byashimov
  • 454
  • 2
  • 6
  • This didn't seem to work for me. It didn't raise an error, but did not GROUP BY the results -- i.e., I have more than one item with the same checksum. – David542 Oct 17 '14 at 19:09
  • Could you explain what exactly you want to get? The code works, I've just tested it. It returns one item of each checksum -- distinct does same too. Take a look at this [answer](http://stackoverflow.com/questions/581521/whats-faster-select-distinct-or-group-by-in-mysql): in most cases they're synonyms. – byashimov Oct 18 '14 at 07:25