DEV Community

Cover image for Django queryset filters: GT, LT, GTE, LTE
Odipo Otieno (KwargDevs)
Odipo Otieno (KwargDevs)

Posted on

Django queryset filters: GT, LT, GTE, LTE

In Django, the following queryset filters are used to perform comparisons in database queries:

  1. gt (greater than): This filter selects objects where the specified field is greater than the given value. For example:
   restaurants = Restaurant.objects.filter(price__gt=30.00)
Enter fullscreen mode Exit fullscreen mode

This query will retrieve all Restaurant objects where the price field is greater than 30.00.

  1. lt (less than): This filter selects objects where the specified field is less than the given value. For example:
   restaurants = Restaurant.objects.filter(price__lt=10.00)
Enter fullscreen mode Exit fullscreen mode

This query will retrieve all Restaurant objects where the price field is less than 10.00.

  1. gte (greater than or equal to): This filter selects objects where the specified field is greater than or equal to the given value. For example:
   restaurants = Restaurant.objects.filter(price__gte=10.00)
Enter fullscreen mode Exit fullscreen mode

This query will retrieve all Restaurant objects where the price field is greater than or equal to 10.00.

  1. lte (less than or equal to): This filter selects objects where the specified field is less than or equal to the given value. For example:
   restaurants = Restaurant.objects.filter(price__lte=30.00)
Enter fullscreen mode Exit fullscreen mode

This query will retrieve all Restaurant objects where the price field is less than or equal to 30.00.

In the code you provided, these filters are used to perform price-based filtering on the Restaurant model. Depending on the selected price ranges, the code applies the appropriate filter using these queryset filters to retrieve the desired restaurants.

Top comments (0)