Code With Python
39.2K subscribers
886 photos
27 videos
22 files
769 links
This channel delivers clear, practical content for developers, covering Python, Django, Data Structures, Algorithms, and DSA – perfect for learning, coding, and mastering key programming skills.
Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
• Fetch related 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