TGViewer
Learn Python Coding Learn Python Coding @pythonre · 40.9K subscribers
Post #8653 763
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
More from @pythonre
  1. Oct 17, 2026😰 15-Hour "Python for Data Science" Course ⚡️ Learn Python for Data Science https://enghu…
  2. Oct 13, 2026https://substack.com/@husseinsheikho?utm_source=share&utm_medium=android&r=3hwnr8 Follow m…
  3. Oct 10, 2026📚 Download 10 Python books for FREE: 1. Think Python — O’Reilly https://t.co/X7y3pX68IW 2…
  4. Oct 7, 2026Python Lists: A Quick Reference 🐍 * Definition: Lists are ordered, mutable collections th…
  5. Oct 7, 2026📱 270 tools for Python developers The repository contains: 🫡 Linters and formatters; 🫡…
  6. Oct 7, 2026Hands On Python Data Science - Data Science Bootcamp Master Python for Data Science with R…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →