Where

  • 1. Example models

    1. models

    
    
                  class Customer(models.Model):
                    first_name = models.CharField(max_length=255)
                    last_name = models.CharField(max_length=255)
                    email = models.EmailField(unique=True)
    
                    def __str__(self):
                        return f"{self.first_name} {self.last_name}"
    
    
                class Category(models.Model):
                    name = models.CharField(max_length=255)
    
                    def __str__(self):
                        return self.name
    
    
                class Product(models.Model):
                    name = models.CharField(max_length=255)
                    description = models.TextField()
                    price = models.DecimalField(max_digits=10, decimal_places=2)
                    category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
                    stock = models.PositiveIntegerField(default=0)
    
                    def __str__(self):
                        return self.name
    
                
  • 2. where condition

    1. Basic where

    
                   product= Product.objects.filter(name="Smartphone")
                   

    Output :

    
                   'SELECT
                          "product"."id",
                          "product"."name",
                          "product"."description",
                          "product"."price",
                          "product"."category_id",
                          "product"."stock"
                  FROM 
                      "product" 
                  WHERE 
                      "product"."name" = \'Smartphone\
    
                  

    2. Multiple where

    
                    # 1. AND (2 ways)
                    Emp.objects.filter(age=28,name="Ava Martinez")
                    Emp.objects.filter(Q(age=28) & Q(name="Ava Martinez"))
    
                    # 2. OR 
                    Emp.objects.filter(Q(age=28) | Q(name="Ava Martinez"))
    
                    # 3. NOT
                    Emp.objects.filter(~Q(age=28))
    
                    
  • 3. LIKE
    1. Contains (substring search):

    name__containsis a field lookup that checks for the presence of the substring "art" anywhere in the name field, regardless of its position. “art” in their name, such as “Smartphone,” “Artisan,” or “Cart.”

    
                Product.objects.filter(name__contains="art")
                

    Output:

    
                'SELECT
                        "product"."id",
                        "product"."name",
                        "product"."description",
                        "product"."price",
                        "product"."category_id",
                        "product"."stock"
                FROM
                     "product"
                WHERE
                    "product"."name" LIKE \'%art%\'
    
                
    2. Starts with:

    name__startswith : It returns a queryset containing all products whose names start with “T,” such as “Tablet,” “TV,” or “T-shirt.”

    
                Product.objects.filter(name__startswith="T")
                

    Output:

    
                'SELECT
                    "product"."id",
                    "product"."name",
                    "product"."description",
                    "product"."price",
                    "product"."category_id",
                    "product"."stock"
                FROM 
                    "product"
                WHERE
                     "product"."name" LIKE \'T%\' 
            
    3. Ends with:

    name__endswith : It returns a queryset containing all products whose names end with “top,” such as “Laptop,” “Desktop,” or “Teapot.”

    
            Product.objects.filter(name__endswith="top")
            

    Output:

    
            'SELECT
                    "product"."id",
                    "product"."name",
                    "product"."description",
                    "product"."price",
                    "product"."category_id",
                    "product"."stock"
            FROM 
                "product"
            WHERE 
                "product"."name" LIKE \'%top\' 
            
  • 4. Comparison : > , <
    1. Greater than
    
            Product.objects.filter(price__gt=199)
            

    Output:

    
            'SELECT
                "product"."id",
                "product"."name",
                "product"."description",
                "product"."price",
                "product"."category_id",
                "product"."stock"
        FROM 
            "product"
        WHERE 
            "product"."price" > \'199\'
                
    2. Less than:
    
                Product.objects.filter(price__lt=199)
                
  • 5. BETWEEN / NOT BETWEEN
    1. BETWEEN
    
                Product.objects.filter(stock__range=(50, 200))
                

    Output:

    
                'SELECT 
                    "product"."id",
                    "product"."name",
                    "product"."description",
                    "product"."price",
                    "product"."category_id",
                    "product"."stock"
            FROM 
                "product"
            WHERE 
                "product"."stock" BETWEEN 50 AND 200
    
            
    2. NOT BETWEEN
    
            # filter records that do not have an ID in the range of 1 to 3 
            Emp.objects.filter(~Q(id__range=(1,3)))
            </pre>
    
    
                  
  • 6. IN / NOT IN
    1. IN OPERATOR
    
            # fetch objects that have age value 25, 28, or 30
            Emp.objects.filter(age__in=[25,28,30])
            
    2. NOT IN OPERATOR
    
            Product.objects.exclude(category_id=1)
            

    Output:

    
            'SELECT
                    "product"."id",
                    "product"."name",
                    "product"."description",
                    "product"."price",
                    "product"."category_id",
                    "product"."stock"
            FROM 
                "product"
            WHERE NOT 
                ("product"."category_id" = 1)
    
            
    
            # fetch objects that do not have age value 25, 28, 30
            Emp.objects.exclude(age__in=[25,28,30])
            
  • 7. Pattern matching
    
            # STARTS WITH CASE SENSITIVE
            Emp.objects.filter(name__startswith="J")
    
            # STARTS WITH CASE INSENSITIVE
            # i ignores casing
            Emp.objects.filter(name__istartswith="j")
    
            # ENDS WITH CASE SENSITIVE
            Emp.objects.filter(name__endswith="e")
    
            # CONTAINS 
            # checks for 'doe' in name irrespective of the case
            Emp.objects.filter(name__icontains='doe')
    
            # IS NULL
            Emp.objects.filter(age__isnull=True)
    
            # IS NOT NULL
            Emp.objects.filter(age__isnull=False)