Teebone Ding Technical Blog

Django, Python, Javascript, Pig, and Hadoop.

Ordering in Selecting Objects in Django Model

Data ordering

While retreiving data from Django Model, we might want data that retreived in some ordering. (alphabet, created time, and etc.) Simply use Model.objects.order_by() function.

The Model class example is the same as selecting objects in django model.

model.py
1
2
3
4
5
6
7
8
9
class Request(models.Model):
  sender = models.CharField(max_length=200)
  sender_place = models.CharField(max_length=200)
  receiver = models.CharField(max_length=200)
  receiver_place = models.CharField(max_length=200)
  message = models.TextField()  # message leaved by sender
  vid_id = models.CharField(max_length=200)  # Video URL from YouTube, Vimeo, ... film share web sites
  share_hash = models.CharField(max_length=200) # Share hash code that the reciever can click to watch
  create_time = models.DateTimeField(auto_now_add=True)      # share link create time

For example, order by “sender”:

1
Request.objects.order_by("sender")

This will return a list of objects that order by the alphabet of sender’s name. If you would like to select data by reverse ordering, add minus sigh (-) before the Field name:

1
Request.objects.order_by("-created_time")

This will return a list with the latest created object in the first place. You can also order by multiple Fields by adding a second ordering like this:

1
Request.objects.order_by("sender", "-created_time")

And this will return a list that order by sender’s name first. If there exist a sender’s name with more than one object, they will be ordered by reverse created time then.

Default ordering

Always retreive data in the same ordering by calling Model.objects.order_by() could be redundant. We can denote a default ordering in Model class and the retreived data will order by the default ordering. Add class Meta in the original Model:

model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
class Request(models.Model):
  sender = models.CharField(max_length=200)
  sender_place = models.CharField(max_length=200)
  receiver = models.CharField(max_length=200)
  receiver_place = models.CharField(max_length=200)
  message = models.TextField()  # message leaved by sender
  vid_id = models.CharField(max_length=200)  # Video URL from YouTube, Vimeo, ... film share web sites
  share_hash = models.CharField(max_length=200) # Share hash code that the reciever can click to watch
  create_time = models.DateTimeField(auto_now_add=True)      # share link create time

  # Default ordering: reverse create_time
  class Meta:
      ordering = ['-create_time']

The class Meta is embedded in class Request. now we can retrieve data with Request.objects.all() that is ordered by reverse created time. This can save calling order_by("-created_time") every time.

References

Django book Chapter 5 (Model) Ordering Data

Comments