8. How to filter a queryset with criteria based on comparing their field values¶
Django ORM makes it easy to filter based on fixed values.
To get all
User objects with
first_name starting with
you can do
What if you want to compare the first_name and last name?
You can use the
F object. Create some users first.
Now you can find the users where
In : User.objects.filter(last_name=F("first_name")) Out: <QuerySet [<User: Guido>]>
F also works with calculated field using annotate. What if we wanted users whose first and last names have same letter?
You can set the first letter from a string using
Substr("first_name", 1, 1), so we do.
In : User.objects.create_user(email="[email protected]", username="Tim", first_name="Tim", last_name="Teters") Out: <User: Tim> #... In : User.objects.annotate(first=Substr("first_name", 1, 1), last=Substr("last_name", 1, 1)).filter(first=F("last")) Out: <QuerySet [<User: Guido>, <User: Tim>]>
F can also be used with
__lt and other expressions.