Django Tips:
Advanced Django Tips
Q Objects for Complex Queries:
from django.db import models
class Ticker(models.Model):
symbol = models.CharField(max_length=50, unique=True)
class TickerPrice(models.Model):
ticker = models.ForeignKey(
Ticker, on_delete=models.CASCADE, related_name="ticker_prices"
)
price = models.DecimalField(max_digits=7, decimal_places=2)
close_date = models.DateField()today_and_yesterday_prices = TickerPrice.objects.filter(
models.Q(close_date=today) | models.Q(close_date=yesterday)
)
# Fetching the ticker prices with close dates of today or yesterday.
today_and_yesterday_greater_than_1000 = TickerPrice.objects.filter(
models.Q(price__gt=1000),
(models.Q(close_date=today) | models.Q(close_date=yesterday)),
)
# Getting all prices with a close date of today or yesterday
# with a price greater than 1000
today_and_yesterday_greater_than_1000_without_BRK = (
TickerPrice.objects.filter(
models.Q(price__gt=1000),
~models.Q(ticker__symbol__startswith="BRK"),
(models.Q(close_date=today) | models.Q(close_date=yesterday)),
)
)
# Fetching all ticker prices greater than 1000 that don’t start
# with BRK with close dates of either today or yesterday.
# We added the condition that the ticker’s symbol does not start with BRKPrefetch Related and Select Related:
Annotate Querysets to Fetch Specific Values
Use Prefetch Objects to Control Your Prefetch Related
Define Custom Query Sets and Model Managers for Code Reuse
Use of functools.partial in Django
Creating many upload_to callables for FileFields
upload_to callables for FileFieldstransaction.on_commit() callbacks
transaction.on_commit() callbacksDatabase functions
Last updated