catherine
catherine

Reputation: 22808

distinct() is not working

I'm trying to group duplicate values but it's not working. I've google many times and they point distinct() function. No matter what I do is not working. I try distinct() before in other queries (not mine) and it's working, now I'm using it, it's not working.

Here are my codes:

models.py

 class Transaction(models.Model):
    payee = models.CharField(
        max_length=255
        )

views.py

 transactions = Transaction.objects.values_list('payee', flat=True).distinct()

output:

 [u'YOUR LOCAL SUPERMARKET', 
  u'CITY OF SPRINGFIELD', 
  u'SPRINGFIELD WATER UTILITY', 
  u'DEPOSIT', 
  u'DEPOSIT'] 

Notice the output there is duplicate for DEPOSIT

Upvotes: 2

Views: 1202

Answers (1)

Henrik Andersson
Henrik Andersson

Reputation: 47222

When you have defined an ordering the distinct() will take these fields into account when trying to do the SQL and thusly can return strange results.

You can therefore:

  • either skip ordering,

  • call an empty order_by() in your query,

  • you can define what fields you want to have distinct() on.

So on your case the query would be

Transaction.objects.order_by('payee').distinct('payee')

this will disregard any ordering you might have and it will also be a bit more clearer to whats happening but this comes at the cost of only being available in PostGresSQL.

Read more here in the docs

Upvotes: 5

Related Questions