Advanced usage of the queryset
We studied the basics of querysets that allow you to interact with the data. In specific cases, it is necessary to perform more complex actions on the data.
Using an OR operator in a queryset
In queryset filters, we use a comma to separate filters. This point implicitly means a logical operator AND
. When applying an OR
operator, we are forced to use the Q
object.
This Q
object allows you to set complex queries on models. For example, to select the projects of the customers Me
and Nobody
, we must add the following lines in our view:
from TasksManager.models import Task, Project from django.shortcuts import render from django.db.models import Q def page(request): projects_list = Project.objects.filter(Q(client_name="Me") ...
Get Django: Web Development with Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.