Let’s say we want to find a product that is 20 dollars. Pretty simple
queryset = Product.objects.filter(unit_price=20)What if we want to find all the products that are expensive than 20 dollars. We cant use a
logical operator here({unit_price>20}), since the filter method doesnt accept that. This is
because that returns a boolean.
In order to work around this, we need to pass a keyword argument to the filter method. After the field name, we type two underscores followed by a lookup type. See below
queryset = Product.objects.filter(unit_price__gt=20) #gt means greater than, gte means >= and so on.
queryset = Product.objects.filter(unit_price__range=(20, 30)) #returns products with price within the range of 20 and 30Assuming we want to render all the products within the price range of 20 and 30. See below,
views.py
from django.shortcuts import renderfrom store.models import Product
# Create your views here.def say_hello(request): queryset = Product.objects.filter(unit_price__range=(20, 30))
return render(request, 'hello.html', {'products': list(queryset)})We are passing the products data to our hello.html file. So we need to go into our hello.html file and render the products there.
hello.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <ul> {% for product in products %} <li>{{product.title}}</li> {% endfor %} </ul></body></html>In the html file, we are looping through all the products being received from the views.py file and rendering it in an unordered list.
We can also filter across relationships
For instance, we want to find all the products inside collection number 1.
from django.shortcuts import renderfrom store.models import Product
# Create your views here.def say_hello(request): queryset = Product.objects.filter(collection__id__range=(1, 2, 3)) #returns all the products in any of those collections
return render(request, 'hello.html', {'products': list(queryset)})So far, we have only talked about filtering based on numbers, how do we filter objects based on strings.
from django.shortcuts import renderfrom store.models import Product
# Create your views here.def say_hello(request): queryset = Product.objects.filter(title__contains='coffee') # returns the products with coffee in their title
return render(request, 'hello.html', {'products': list(queryset)})The above lookup type is case sensitive. So to perform a case insensitive lookup type, we use “icontains”. See below
queryset = Product.objects.filter(title__icontains='coffee')There are other lookup types like
__startswith__endswithas well as their case insensitive equivalents.
Filtering dates..
last_update__year=2021Checking for null
description__isnull=True # returns products with a null description