Teebone Ding Technical Blog

Django, Python, Javascript, Pig, and Hadoop.

Selecting Objects in Django Model

When we talk about database, the dumb way to select objects in Django is using raw SQL scripts. We don’t use SQL directly in Django due to security issues and cross-platform achievement. Using Django database API can avoid most SQL secure holes and you don’t have to learn much about database selecting languages which might be slightly different between several Django supported databases. I am going to talk about a little (my notes) in selecting objects in Django model.

Filtering Objects

Here is an example model.py. I created a class “Request” that is a model stores information about a man sends a message with a youtube video link.

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

If you would like to select objects with the sender field equals to “Alan”, use Model.objects.filter() like this:

1
Request.objects.filter(sender="Alan")

This code filters all objects with field sender equals to “Alan”. The similar SQL is the WHERE clause.

1
SELECT * FROM Request WHERE sender = 'Alan';

You can filter ojbects with multiple fields in Model.objects.filter(). Just use comma (,) to seperate them. If you would like to filter objects with sender field that “contains” a term, plus __contains suffix in Model.objects.filter():

1
Request.objects.filter(sender__contains="John")

Senders like “John”, “Johnson” will be selected. The corresponding SQL is the LIKE statement. For example:

1
SELECT * FROM Request WHERE sender LIKE '%John%';

All lookup suffixes are put in django book appendix B.

Get an object

In Django one can also retreive one object by Model.objects.get(). This will return only one object from the Model. Model.objects.filter() returns a list for you. If there are more than one object or no objects return from Model.objects.get(), an error will be returned. The usage of Model.objects.get() is similar to Model.objects.filter(). For instance, get the object with receiver equals to “Annie”:

1
Request.objects.get(receiver="Annie")

That’s all for this post! The references are put below.

References

Django book Chapter 5 (Model) Selecting Objects

Django book Appendix B (Database API) Field Lookups

Comments