2013-03-25 17 views
14

Làm thế nào tôi sẽ làm các truy vấn sau đây:ON DISTINCT trong django

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

Về cơ bản, tôi cần phải có được tất cả OrderNotes mục, riêng biệt trên shared_note. Khi tôi thử và làm điều này, tôi nhận được:

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

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

Tôi đang sử dụng mysql và không thể thay đổi db tại đây. Điều gì sẽ là workaround trong django?

+0

Bạn có thể gửi mô hình này? – Ngenator

Trả lời

47
OrderNotes.objects.filter(item=item).values_list('shared_note', flat=True).distinct() 
+5

Nếu bạn muốn có các đối tượng đầy đủ và không chỉ các giá trị duy nhất? :-) Bắt một chút khó khăn ... –

4

Đây là tốt nhất mà tôi đã đưa ra:

>>> 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) 
Các vấn đề liên quan