Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you order lists in the same way QuerySets are ordered in Django?

I have a model that has an ordering field under its Meta class. When I perform a query and get back a QuerySet for the model it is in the order specified. However if I have instances of this model that are in a list and execute the sort method on the list the order is different from the one I want. Is there a way to sort a list of instances of a model such that the order is equal to that specified in the model definition?

like image 339
hekevintran Avatar asked Dec 29 '25 11:12

hekevintran


2 Answers

Not automatically, but with a bit of work, yes. You need to define a comparator function (or cmp method on the model class) that can compare two model instances according to the relevant attribute. For instance:

class Dated(models.Model):
  ...
  created = models.DateTimeField(default=datetime.now)

  class Meta:
    ordering = ('created',)

  def __cmp__(self, other):
    try:
      return cmp(self.created, other.created)
    except AttributeError:
      return cmp(self.created, other)
like image 142
Carl Meyer Avatar answered Dec 31 '25 00:12

Carl Meyer


The answer to your question is varying degrees of yes, with some manual requirements. If by list you mean a queryset that has been formed by some complicated query, then, sure:

queryset.order_by(ClassName.Meta.ordering)

or

queryset.order_by(instance._meta.ordering)

or

queryset.order_by("fieldname") #If you like being manual

If you're not working with a queryset, then of course you can still sort, the same way anyone sorts complex objects in python:

  • Comparators
  • Specifying keys
  • Decorate/Sort/Undecorate

See the python wiki for a detailed explanation of all three.

like image 29
David Berger Avatar answered Dec 31 '25 00:12

David Berger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!