tgoop.com/DataScience4/8652
Create:
Last Update:
Last Update:
💡 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.
BY Code With Python
Share with your friend now:
tgoop.com/DataScience4/8652
