How to filter objects and get unique data by field using distinct in Django 1.3


So, you have field that contains insurer, agent name. For instance:

1
2
3
4
5
6
7
Insurer  | Agent
======== | =====
Tommy    | AXA
Joko     | CommonWealth
Falcon   | CommonWealth
Sumito   | Wilis
Tarno    | AXA

You want to search unique agent in the database. Then you can use values and distinct. Remember, disticnt doesn’t make unique result by field. If you want distinct by field, then you should use values and disticnt together. Eg :

1
unique_insurance = Insurance.objects.order_by(‘agent’).values(‘agent’).distinct()

This will show unique agent field :

1
[ ‘AXA’, ‘CommonWealth’, ‘Wilis’ ]

Easy right ? 😀


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.