entry = Entry.objects.get(pk=1)
entry.rating = 5
entry.save()
• Update multiple objects in a single query.
Entry.objects.filter(pub_date__year=2022).update(rating=0)
• Remove an object from a
ManyToManyField.entry.tags.remove(tag1)
VII. Deleting Objects
• Delete a single object.
entry = Entry.objects.get(pk=1)
entry.delete()
• Delete multiple objects in a single query.
Entry.objects.filter(rating=0).delete()
VIII. Spanning Relationships
• Filter based on a related model's field.
Entry.objects.filter(author__name="John Doe")
• Use a field lookup on a related model.
Entry.objects.filter(author__name__startswith="John")
• Access related objects from the "one" side of a relationship.
author = Author.objects.get(name="John Doe")
authors_entries = author.entry_set.all()
IX. Aggregation
(Requires
from django.db.models import ...)• Calculate aggregate values over an entire queryset.
from django.db.models import Avg
avg_rating = Entry.objects.aggregate(Avg('rating'))
• Average (
Avg).Entry.objects.aggregate(average_rating=Avg('rating'))• Sum (
Sum).Entry.objects.aggregate(total_ratings=Sum('rating'))• Maximum (
Max) and Minimum (Min).Entry.objects.aggregate(max_r=Max('rating'), min_r=Min('rating'))• Count (
Count).Entry.objects.aggregate(num_entries=Count('pk'))• Count distinct values.
Entry.objects.aggregate(num_authors=Count('author', distinct=True))X. Annotation
• Add a calculated field to each object in a queryset.
from django.db.models import Count
authors = Author.objects.annotate(entry_count=Count('entry'))
• Access an annotated value.
for author in authors:
print(author.name, author.entry_count)
• Get results as a list of dictionaries.
Entry.objects.values('headline', 'author__name')XI. F() Expressions
• Import
F() expressions.from django.db.models import F
• Update a field based on its own value.
Entry.objects.filter(pk=1).update(rating=F('rating') + 1)• Filter by comparing two fields on the same model.
Entry.objects.filter(rating__gt=F('author__rating'))XII. Q() Objects
• Import
Q() objects for complex queries.from django.db.models import Q
• Create an
OR query.Entry.objects.filter(Q(headline__startswith='A') | Q(headline__startswith='B'))
• Create a
NOT query.Entry.objects.filter(~Q(headline__icontains='boring'))
XIII. QuerySet Evaluation
• Get the count of objects efficiently.
count = Entry.objects.count()
• Check if any objects exist efficiently.
exists = Entry.objects.filter(rating=5).exists()
• Get the count (evaluates the full queryset).
count = len(Entry.objects.all())
• Check for existence (evaluates the full queryset).
if Entry.objects.filter(rating=5): # True if queryset is not empty
...
• Iteration (evaluates the queryset).
for entry in Entry.objects.all():
print(entry.headline)
XIV. Optimization