Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DISTINCT ON in django [duplicate]

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?

like image 829
David542 Avatar asked Mar 25 '13 22:03

David542


People also ask

How do I remove duplicates in Django ORM?

You can do this in the ORM directly without the Python loop by doing something like: Address. objects. exclude(pk__in=d. values('pk, flat=True)).

How do you prevent duplicates in Django?

Use the get_or_create() Method in Django When we create duplicate objects multiple times, this method helps us avoid creating them multiple times.

How do I get distinct in Django?

One way to get the list of distinct column names from the database is to use distinct() in conjunction with values() .

How do I merge two QuerySets in Django?

You can also use the chain() method from the Itertools module, which allows you to combine two or more QuerySets from different models through concatenation. Alternatively, you can use union() to combine two or more QuerySets from different models, passing all=TRUE if you want to allow duplicates.


2 Answers

OrderNotes.objects.filter(item=item).values_list('shared_note', flat=True).distinct()
like image 177
catherine Avatar answered Oct 19 '22 20:10

catherine


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)
like image 33
David542 Avatar answered Oct 19 '22 20:10

David542