Ticket #9415: order-by-reset.diff

File order-by-reset.diff, 2.1 KB (added by Alex, 7 years ago)

patch that adds the proposed reset kwarg, backwards compatible

  • django/db/models/query.py

    diff --git a/django/db/models/query.py b/django/db/models/query.py
    index 5b9f504..a6b8f9f 100644
    a b class QuerySet(object): 
    553553        """
    554554        self.query.select_related = other.query.select_related
    555555
    556     def order_by(self, *field_names):
     556    def order_by(self, *field_names, **kwargs):
    557557        """
    558558        Returns a new QuerySet instance with the ordering changed.
    559559        """
     560        # we use **kwargs because python can't do *args, reset=True :(
    560561        assert self.query.can_filter(), \
    561562                "Cannot reorder a query once a slice has been taken."
    562563        obj = self._clone()
    563         obj.query.clear_ordering()
     564        if kwargs.get('reset', True):
     565            obj.query.clear_ordering()
    564566        obj.query.add_ordering(*field_names)
    565567        return obj
    566568
  • tests/modeltests/ordering/models.py

    diff --git a/tests/modeltests/ordering/models.py b/tests/modeltests/ordering/models.py
    index a53d93c..fbd0b88 100644
    a b class Article(models.Model): 
    2424    def __unicode__(self):
    2525        return self.headline
    2626
     27class Value(models.Model):
     28    name = models.CharField(max_length=100)
     29    count = models.IntegerField()
     30   
     31    def __unicode__(self):
     32        return "%s - %s" % (self.name, self.count)
     33
    2734__test__ = {'API_TESTS':"""
    2835# Create a couple of Articles.
    2936>>> from datetime import datetime
    __test__ = {'API_TESTS':""" 
    8693>>> Article.objects.extra(select={'order': 'pub_date'}, order_by=['order', 'headline'])
    8794[<Article: Article 1>, <Article: Article 2>, <Article: Article 3>, <Article: Article 4>]
    8895
     96# using the reset = False kwarg on order_by shouldn't reset ordering
     97>>> _ = Value.objects.create(name='Apple', count=3)
     98>>> _ = Value.objects.create(name='Apple', count=5)
     99>>> _ = Value.objects.create(name='Apple', count=4)
     100>>> _ = Value.objects.create(name='Bannana', count=4)
     101>>> qs = Value.objects.order_by('-count')
     102>>> qs.order_by('-name', reset=False)
     103[<Value: Apple - 5>, <Value: Bannana - 4>, <Value: Apple - 4>, <Value: Apple - 3>]
     104
    89105"""}
Back to Top