21
votes

How would I do the following query:

OrderNotes.objects.filter(item=item).distinct('shared_note')

Basically, I need to get all OrderNotes items, distinct on shared_note. When I try and do this I get:

    raise NotImplementedError('DISTINCT ON fields is not supported by this database backend')

NotImplementedError: DISTINCT ON fields is not supported by this database backend

I am using mysql and cannot change the db here. What would be the workaround in django?

2

2 Answers

72
votes
OrderNotes.objects.filter(item=item).values_list('shared_note', flat=True).distinct()
7
votes

This is the best I came up with:

>>> items, item_ids = [], []
>>> for item in OrderNotes.objects.filter(shared_note=219):
...     if item.shared_note not in item_ids:
...         items.append(item)
...         item_ids.append(item.shared_note)