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.
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.
1 2 3 4 5 6 7 8 9
If you would like to select objects with the
sender field equals to “Alan”, use
Model.objects.filter() like this:
This code filters all objects with field
sender equals to “Alan”. The similar SQL is the
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
Senders like “John”, “Johnson” will be selected. The corresponding SQL is the
LIKE statement. For example:
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”:
That’s all for this post! The references are put below.