Django Querying¶
[[Django Raw SQL Queries]]
Get¶
You should use filter if you want to get multiple objects
get_or_create()¶
obj, created = Person.objects.get_or_create(
    first_name='John',
    last_name='Lennon',
    defaults={'birthday': date(1940, 10, 9)},
)
Filtering¶
SQL where id in [1,3,4,5,6....];¶
.filter(id=1, name=1) vs .filter(id=1).filter(name=1)¶
Chaining multiple filter() in Django, is this a bug? - Stack Overflow
- they only might be different when dealing with foreign keys
Q Objects¶
Useful for OR in your WHERE clause
Django 4.1 added XOR
- .objects.filter(a=1, b=1)- ANDs things together
from django.db.models import Q
lookup = Q(question__startswith='Who') | Q(question__startswith='What')
Poll.objects.filter(lookup)
F Expressions¶
Field Expression
Get the value of that column
Order by DESC¶
Order by Nulls Last¶
Query Expressions | Django Docs
Subqueries¶
Get the instances from a QuerySet?¶
- Convert it into a list and it will make the database call
UUIDField as primary key
- cluster index?- don't use UUIDs
 
Choices (Django 2)¶
  AGE_RATING =[
    ("G","General Audiences"),
    ("PG","Parental Guidance Suggested"),
    ("PG-13","Inappropriate for Children Under 13" ),
    ("R", "Restricted"),
    ("NC-17","Adults Only"),
  ]
age_rating = models.CharField(max_length= 5, choices = AGE_RATING, default = "GENERAL AUDIENCE")
Choices (Django 3)¶
Aggregation¶
To use the aggregation functions, you need
from django.db.models import Sum, Min, Max, Avg
>>> City.objects.aggregate(Sum('population'))
{'population_sum': 1234567}
Annotation¶
Adding a new column to the result
>>> result = City.objects.annotate(future_population=F('population') * 1.05)
>>> result.future_population
12345
select_related¶
Inner join for a 1 → n foreign key
Fetch the foreign keys
prefetch_related¶
Many to Many relationship
OrderProduct is the many to many Order ↔ Product table
WITH order_ids AS (
  SELECT id
  FROM Order
)
SELECT *
FROM Product
  INNER JOIN OrderProduct
    ON Product.id = OrderProduct.product_id
WHERE OrderProduct.order_id IN (SELECT id FROM order_ids)
Many-to-many¶
Create an entry in a many¶
List many to many¶
Updating¶
django post_save signals on update
Calls post_save signal
Doesn't call post_save signal
- converted directly into SQL
  
    
      Last update:
      2023-04-24