[Fixed]-Django ORM: Apply ordering to raw query sets

1👍

If you want a raw queryset to be ordered by different fields, you can add them to the ORDER BY clause.

ob = Shop.objects.raw('SELECT * from shops GROUP BY
 (duplicate_field_name) having COUNT(*) = 1 ORDER BY check_in, check_out, location')

if you want the order to be reversed for a particular field you can change it as

ob = Shop.objects.raw('SELECT * from shops GROUP BY
 (duplicate_field_name) having COUNT(*) = 1 ORDER BY check_in, check_out DESC, location')

If the ordering is going to be dynamic, you can create the querystring dynamically.

qs = ''SELECT * from shops GROUP BY
 (duplicate_field_name) having COUNT(*) = 1'

# some other code here to decide what your ordering is example
order_fields = ['id','location','check_in','check_out']

qs = qs + "ORDER BY " + ",".join(order_fields)

Then you can query as before

Shop.objects.raw(qs)
👤e4c5

Leave a comment