27
loading...
This website collects cookies to deliver better user experience
class Author(models.Model):
nickname = models.CharField(max_length=20, null=True, blank=True)
firstname = models.CharField(max_length=20)
lastname = models.CharField(max_length=40)
birth_date = models.DateField()
class Book(models.Model):
author = models.ForeignKey(Author, related_name="books", on_delete=models.CASCADE)
title = models.CharField(unique=True, max_length=100)
category = models.CharField(max_length=50)
published = models.DateField()
price = models.DecimalField(decimal_places=2, max_digits=6)
rating = models.IntegerField()
filter
method. Field lookups consist of the field and a suffix defining the lookup type. If no suffix is defined, the default behavior is equivalent to using the exact suffix.books = Book.objects.filter(title="Crime and Punishment")
books = Book.objects.filter(title__startswith="Crime")
# Books published in 2021
books = Book.objects.filter(published__year=2021)
# Books published in the year 2000 or after
books = Book.objects.filter(published__year__gte=2000)
# Books published before the year 2000
books = Book.objects.filter(published__year__lt=2000)
range
lookup to query objects within a specific time range.start_date = datetime.date(2021, 1, 1)
end_date = datetime.date(2021, 1, 3)
books = Book.objects.filter(published__range=(start_date, end_date))
from django.db.models import Q
# Get all books published in 2018 or 2020
books = Book.objects.filter(Q(published__year=2018) | Q(published__year=2020))
# Get all books published in
from django.db.models import F
# Query books published by authors under 30 years old (this is not exactly true because years vary in length)
books = Book.objects.filter(published__lte=F("author__birth_date") + datetime.timedelta(days=365*30))
from django.db.models import F
book = Book.objects.get(title="Crime and Punishment")
book.update(rating=F("rating") + 1)
from django.db.models import F, Value as V
from django.db.models.functions import Concat
author = Author.objects.annotate(full_name=Concat(F("firstname"), V(" "), F("lastname")))
full_name
to our query results. It will contain a concatenation of the authors firstname and lastname done using the Concat function, F expressions, and Value.from django.db.models import F
from django.db.models.functions import Coalesce
books = Author.objects.annotate(known_as=Coalesce(F("nickname"), F("firstname")))
known_as
, that holds the value we wanted for each Author in the result set.# Add a new field with the authors age at the time of publishing the book
books = Book.objects.annotate(author_age=F("published") - F("author__birth_date"))
# Add a new field with the rating multiplied by 100
books = Book.objects.annotate(rating_multiplied=F("rating") * 100)
from django.db.models import Avg
result = Book.objects.aggregate(Avg("price"))
# {'price__avg': Decimal('13.50')}
result = Book.objects.aggerate(Max("price"))
# {'price__max: Decimal('13.50')}
result = Book.objects.aggerate(Min("published"))
# {'published__min': datetime.date(1866, 7, 25)}
from django.db.models import Count
authors = Author.objects.annotate(num_books=Count("books"))
# Calculate average prices for books in all categories.
Book.objects.values("category").annotate(Avg("price"))
# {'category': 'Historical fiction', 'price__avg': Decimal('13.9900000000000')}, {'category': 'Romance', 'price__avg': Decimal('16.4950000000000')}
from django.db.models import F, Q, Value, When, Case
from decimal import Decimal
books = Book.objects.annotate(discounted_price=Case(
When(category="Romance", then=F("price") * Decimal(0.95)),
When(category="Historical fiction", then=F("price") * Decimal(0.8)),
default=None
))