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)})
Top comments (0)