[Fixed]-Django Models – SELECT DISTINCT(foo) FROM table is too slow

1👍

Thank you @solarissmoke for the pointer to connection.queries.

I was expecting to see

SELECT DISTINCT refdate FROM myTable

Instead, I got

SELECT DISTINCT refdate, itemIndex, itemType FROM myTable ORDER BY itemIndex, refdate, itemType. 

I then looked at myTable defined in models.py.

unique_together = (('nodeIndex', 'refdate', 'nodeType'), )
ordering = ['nodeIndex', 'refdate', 'nodeType']

From Interaction with default ordering or order_by

normally you won’t want extra columns playing a part in the result, so clear out the ordering, or at least make sure it’s restricted only to those fields you also select in a values() call.

So I tried order_by() to flush the previously defined ordering and voila!

myTable.objects.values('refdate').order_by().distinct()
👤Vishal

0👍

You can try this:

myTable.objects.all().distinct('refdate')

Leave a comment