In your Django application, you might want to sort the results of a search based on the value of a field, for example, in alphabetical order. So, using the Order_by () method can be done.
?
| 12 |
>>> Publisher.objects.order_by("name")[<Publisher: Apress>, <Publisher: O‘Reilly>] |
Similar to the previous all () example, the SQL statement has more than the specified ordering part:
?
| 123 |
SELECT id, name, address, city, state_province, country, websiteFROM books_publisherORDER BY name; |
We can sort any of the fields:
?
| 12345 |
>>> Publisher.objects.order_by("address")[<Publisher: O‘Reilly>, <Publisher: Apress>]>>> Publisher.objects.order_by("state_province")[<Publisher: Apress>, <Publisher: O‘Reilly>] |
If you need to sort the criteria in more than one field (the second field is used in the same way as the value of the first field), you can use multiple parameters, as follows:
?
| 12 |
>>> Publisher.objects.order_by("state_province", "address") [<Publisher: Apress>, <Publisher: O‘Reilly>] |
We can also specify a reverse sort, preceded by a minus-prefix:
?
| 12 |
>>> Publisher.objects.order_by("-name")[<Publisher: O‘Reilly>, <Publisher: Apress>] |
Although flexible, it is a bit verbose to use order_by () every time. Most of the time you will typically only sort certain fields. In this case, Django allows you to specify the default ordering of the model:
?
| 12345678910111213 |
class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() def __unicode__(self): return self.name **class Meta:** **ordering = [‘name‘]** |
Now, let's touch on a new concept. Class meta, embedded in the definition of the Publisher class (if class Publisher is shelf, then the class meta will indent 4 spaces below it – in Python's tradition). You can use the Meta class in any of the model classes to set some options related to a particular model. In Appendix B there is a complete reference to all the options in Meta, and now we're going to focus on the ordering option. If you set this option, the relative return value of the Publisher object will be sorted by the Name field by default, unless you specifically use order_by () when you retrieve it, or when you use the Django database API to retrieve it.
How Django sorts the results of a data query