Django Blog #12: QuerySet Methods

by Alex
Django Blog #12: QuerySet Methods
The ORM in Django is based on QuerySet. A QuerySet is a set of objects from a database that can use filters to constrain results. You already know how to retrieve a single object from the database using the get() method. It can be accessed using Post.objects.get(). Every Django model has at least one manager, and the default manager is called objects. You can query an object(QuerySet) using the model manager. To get all objects from a table, you just need to use the all() method in the default object manager:

>>> all_posts = Post.objects.all()

This way you can create a QuerySet that returns all objects in the database. But it’s important to pay attention to the fact that it’s not yet executed. QuerySets in Django are lazy. They only execute if you force them. This behavior makes the tool extremely efficient. If you don’t save the QuerySet to a variable, but write it directly to the Python shell, the SQL expression in the QuerySet will execute automatically because that was the command:

>>> Post.objects.all()

Filter() method

To filter a QuerySet, you can use the manager’s filter() method. For example, you can get all the posts for 2017 using this query:

Post.objects.filter(publish__year=2017)

You can also filter across multiple fields at once. So, to get all the posts for 2017 written by the author admin, you should use the command:

Post.objects.filter(publish__year=2017, author__username='admin')

This is the same as writing a QuerySet with a chain of filters:

Post.objects.filter(publish__year=2017) \ 
	   .filter(author__username='admin')

Queries with field search methods are written with two underscores, e.g. publish__year, _but the same spelling is used to access fields of related models, e.g. author__username

.

The exclude() method

You can exclude some results from a query using the manager’s exclude() method. For example, you can retrieve all posts for 2017 whose names do not begin with Why:

Post.objects.filter(publish__year=2017) \
	   .exclude(title__startswith='why')

Order_by() method

You can sort the results by field using the manager’s order_by() method. For example, you can get all objects sorted according to theirtitle using this command:

Post.objects.order_by('title')

An ascending arrangement is implied. To place items in descending order, you must use minus as a prefix:

Post.objects.order_by('-title')

Deleting objects

If you want to remove an object, you can do it from the instance with the delete() method:

post = Post.objects.get(id=1) 
post.delete()

Note that deleting objects will also remove any dependent relationships for ForeignKey objects for which on_delete is defined in CASCADE

.

When a QuerySet is executed

Multiple filters can be combined for a QuerySet, but they won’t touch the database until the QuerySet is executed. And it is executed under the following conditions:

  • On the first iteration by QuerySet.
  • When getting a slice, for example Post.objects.all()[:3].
  • When serializing or caching objects.
  • When calling repr() or len().
  • When calling list() directly.
  • When checking QuerySet in other expressions like bool(), or, and or if.

Related Posts

LEAVE A COMMENT