multiple filter
pooyaalamdari
Posted on June 6, 2022
AND
class Product(models.Model):
id = models.CharField(max_length=10, primary_key=True)
title = models.CharField(max_length=225)
slug = models.SlugField()
description = models.TextField()
# 9999.99
unit_price = models.DecimalField(max_digits=6, decimal_places=2)
inventory = models.ImageField()
last_update = models.DateTimeField(auto_now=True)
# then reference collection class here
# PROTECT -> if accidentally delete Collection(Parent), PROTECT will protect our all Products (Child)
collection = models.ForeignKey(Collection, on_delete=models.PROTECT)
# we use plural because we have multiple promotions
# many to many
promotions = models.ManyToManyField(Promotion)
from django.shortcuts import render
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from .models import Product, OrderItem
# Create your views here.
def test_model(request):
# inventory < 10 AND price < 20
queryset = Product.objects.filter(inventory__lt=10, unit_price__lt=20)
return render(request, 'test.html', {'products': list(queryset)})
Q object (OR)
from django.shortcuts import render
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from .models import Product, OrderItem
# Create your views here.
def test_model(request):
# inventory < 10 OR price < 20
queryset = Product.objects.filter(Q(inventory__lt=10) | Q(unit_price__lt=20))
return render(request, 'test.html', {'products': list(queryset)})
Q - AND IS NOT
from django.shortcuts import render
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from .models import Product, OrderItem
# Create your views here.
def test_model(request):
# inventory < 10 AND - IS NOT - price < 20
queryset = Product.objects.filter(Q(inventory__lt=10) & ~Q(unit_price__lt=20))
return render(request, 'test.html', {'products': list(queryset)})
💖 💪 🙅 🚩
pooyaalamdari
Posted on June 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
privacy Caught in the Crunch My Journey from Snacks to 2 Million Exposed Users Privacy
November 30, 2024
devchallenge Submission for the DevCycle Feature Flag Challenge: Feature Flag Funhouse
November 30, 2024