• Fetch related
• Fetch related
• Load only specific model fields.
• Defer loading of specific model fields.
• Execute raw, unmanaged SQL.
• Get results as a list of tuples.
XV. Transactions
• Import the transaction module.
• Run a block of code within a database transaction.
XVI. Managers & Model Methods
• Create a custom
• Add a custom method to a
• Add a custom method to a model for object-specific logic.
#Python #Django #ORM #Database #Backend
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
ForeignKey objects in the same query.entries = Entry.objects.select_related('author').all()• Fetch related
ManyToManyField objects in a separate efficient query.entries = Entry.objects.prefetch_related('tags').all()• Load only specific model fields.
entries = Entry.objects.only('headline')• Defer loading of specific model fields.
entries = Entry.objects.defer('body_text')• Execute raw, unmanaged SQL.
authors = Author.objects.raw('SELECT * FROM myapp_author')• Get results as a list of tuples.
Entry.objects.values_list('headline', 'pub_date')XV. Transactions
• Import the transaction module.
from django.db import transaction
• Run a block of code within a database transaction.
with transaction.atomic():
# All database operations here are either committed together or rolled back.
author.save()
entry.save()
XVI. Managers & Model Methods
• Create a custom
Manager for common queries.class PublishedEntryManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='published')
• Add a custom method to a
QuerySet via its Manager.Entry.objects.get_queryset().by_author("John Doe")• Add a custom method to a model for object-specific logic.
class Entry(models.Model):
#...
def is_recent(self):
return self.pub_date > timezone.now() - timedelta(days=1)
#Python #Django #ORM #Database #Backend
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤1