Code With Python
38.7K subscribers
791 photos
23 videos
21 files
717 links
This channel provides clear, practical content for developers focusing on Python, Django, data structures, algorithms, and DSA.

Admin: @Hussein_Sheikho

Ad & Earn money form your channel:
https://telega.io/?r=nikapsOH
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