Django Querysets

created:

updated:

tags: django queryset

This time, I’m working closely with using Django querysets and I’d like to leave some learnings. I haven’t had much chance to work with querysets and I’m glad for this time.

filter()

“Returns a new Querysets containing objects that match the given lookup parameters.”

exclude()

“Returns a new Querysets containing objects that do not match the given lookup parameters.”

annotate()

“annotate” means in English “to add a short explanation or opinion to a text or image”.

“Annotates each object in the QuerySet with the provided list of query expressions. An expression may be a simple value, a reference to a field on the model (or a related models), or an aggregate expression (averages, sums, etc) that has been computed over the objects that are related to the objects in the QuerySet.”

distinct()

“Returns a new QuerySet that use SELECT DISTINCT in its SQL query. This eliminates duplicate rows from the query results.”

values_list()

We can use this to get a list of certain columns. We can pass flat=True if we only pass in a single field.

>>> Entry.objects.values_list("id", "headline")
<QuerySet [(1, 'First entry'), ...]>
>>> Entry.objects.values_list("id", flat=True).order_by("id")
<QuerySet [1, 2, 3, ...]>

Q Objects

“A Q() object represents an SQL condition that can be used in database-related operations. They make it possible to define and reuse conditions, and combine them using operators such as | (OR), & (AND), and ^ (XOR).

“Returns a QuerySet that will ‘follow’ foreign-key relationships, selecting additional related-object data when it executes its query. This is a performance booster which results in a single more complex query but means later use of foreign-key relationships won’t require database queries.”

Let us suppose that we have the following models:

class ModelOne(models.Model):
    model_two = models.ForeignKey("ModelTwo", on_delete=models.CASCADE)

class ModelTwo(models.Model):
    name = models.CharField(max_length=255)
# Hits the database
model_one = ModelOne.objects.first()
# Hits the database again to get the related ModelTwo object
model_two = model_one.model_two
# Hits the database
model_one = ModelOne.objects.select_related("model_two").first()
# Doesn't hit the database because model_one.model_two has been prepopulated
# in the previous query
model_two = model_one.model_two

select_related() uses JOIN in SQL to query information about the related model.

References