TGViewer
Learn Python Coding Learn Python Coding @pythonre · 40.9K subscribers
Post #8652 475
💡 Top 70 Django ORM Operations

I. Model Definition
(in models.py)

• Define a character field.
from django.db import models
name = models.CharField(max_length=100)

• Define a foreign key relationship (many-to-one).
author = models.ForeignKey('Author', on_delete=models.CASCADE)

• Define a many-to-many relationship.
tags = models.ManyToManyField('Tag')

• Define a model's Meta class for default ordering.
class Meta:
ordering = ['-pub_date']

• Define the string representation of an object.
def __str__(self):
return self.headline


II. Creating Objects

• Create and save an object in one step.
entry = Entry.objects.create(headline="New Title", author=some_author)

• Create an instance and save it separately.
new_author = Author(name="John Doe")
new_author.save()

• Create multiple objects in a single query.
Author.objects.bulk_create([Author(name="A"), Author(name="B")])

• Add an object to a ManyToManyField.
entry.tags.add(tag1, tag2)


III. Retrieving Objects (Basic QuerySets)

• Retrieve all objects.
all_entries = Entry.objects.all()

• Retrieve a single object by a unique constraint (e.g., PK).
entry = Entry.objects.get(pk=1)

• Filter objects that match criteria.
entries = Entry.objects.filter(pub_date__year=2023)

• Exclude objects that match criteria.
entries = Entry.objects.exclude(headline__startswith="Old")

• Get the first object from a queryset.
first_entry = Entry.objects.order_by('pub_date').first()

• Get the last object from a queryset.
last_entry = Entry.objects.order_by('pub_date').last()

• Get an object, or create it if it doesn't exist.
obj, created = Author.objects.get_or_create(name="Unique Name")


IV. Field Lookups for Filtering

• Exact match (case-sensitive).
Entry.objects.filter(headline__exact="Hello World")

• Case-insensitive exact match.
Entry.objects.filter(headline__iexact="hello world")

• Case-sensitive contains.
Entry.objects.filter(headline__contains="World")

• Case-insensitive contains.
Entry.objects.filter(headline__icontains="world")

• Match against a list of values.
Entry.objects.filter(pk__in=[1, 3, 5])

• Greater than (__gt) or greater than or equal (__gte).
Entry.objects.filter(rating__gt=4)

• Less than (__lt) or less than or equal (__lte).
Entry.objects.filter(rating__lte=3)

• Starts with or ends with a string.
Entry.objects.filter(headline__startswith="The")

• Match within a range.
Entry.objects.filter(pub_date__range=["2023-01-01", "2023-03-31"])

• Filter by a date component.
Entry.objects.filter(pub_date__year=2023, pub_date__month=5)

• Check if a field is NULL.
Entry.objects.filter(pub_date__isnull=True)


V. Slicing & Ordering QuerySets

• Slice a queryset (similar to Python lists).
first_ten = Entry.objects.all()[:10]

• Order results in ascending order.
Entry.objects.order_by('headline')

• Order results in descending order.
Entry.objects.order_by('-pub_date')

• Order results randomly.
Entry.objects.order_by('?')


VI. Modifying Objects

• Update a single object's fields.
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 →