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?
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)).
Use the get_or_create() Method in Django When we create duplicate objects multiple times, this method helps us avoid creating them multiple times.
One way to get the list of distinct column names from the database is to use distinct() in conjunction with values() .
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.
OrderNotes.objects.filter(item=item).values_list('shared_note', flat=True).distinct()
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With