2

I have a model that uses the Meta ordering property to make sure that all views that use it display things in the same order.

However, I have one method that needs to use the distinct() method - this does not work after ordering is applied. Is there a built in way to retrieve the original queryset before ordering is applied, or do I need to write a custom Manager class to allow me to do this.

Guy Bowden
  • 4,997
  • 5
  • 38
  • 58

2 Answers2

5

Call order_by() before distinct() with no parameters.

From: https://docs.djangoproject.com/en/1.5/ref/models/querysets/#order-by

If you don’t want any ordering to be applied to a query, not even the default ordering, call order_by() with no parameters.

Just doing a quick test reveals that if you do Foomodel.objects.order_by().distinct('bar') it correctly removes all ORDER BY clauses, even ones defined in Foomodel's Meta.

2
from copy import deepcopy

class ExtendedManager(models.Manager):
    def __init__(self):
        super(ExtendedManager, self).init()
        self.model = deepcopy(self.model)
        if self.model._meta.ordering:
            del self.model._meta.ordering

class MyModel(models.Model):
    ...
    unordered_objects = ExtendedManager()

And normally you should be able to do MyModel.unordered_objects.all(), MyModel.unordered_objects.filter(...).distinct(), etc... And for the ordered querysets, nothing changes !

Ricola3D
  • 2,402
  • 17
  • 16