Queryset API #

Field Lookups #

These are predefined keyword arguments to queryset filter methods to help filter the data. They generally take the form field_name__lookuptype=value e.g. Posts.objects.all().filter(pub_date__lte='2016-01-01') for less than or equal to.

Alternatively if you don’t have a lookup type you can just do field_name=value. This is just synatactic sugar for the default field_name__exact=value.

Relationship spanning #

Related names are set on the model defining a foreign key field with related_name=<related_name>. This can be then used to essentially reverse query from the original model all the model instances with foreign keys references to it. Take this example:

class Department(models.model):
    description = models.TextField()


class Employee(models.model):
    name = models.charField()
    department = models.ForeignKey(
        'Department',
        on_delete=models.CASCADE,
        related_name="employees"
    )
post = Post.objects.get(id=2) # Hits database to get post
user = post.user # Hits database again to get user
post = Post.objects.select_related('users').get(id=2) #
user = post.user # Doesn't hit the database because the post model is already populated with user because of select_related

From a department instance you can get all employees with a foreign key reference to that department with <department_model>.employees.all(). Without setting the related field you would have to do <department_model>.employee_set.all().

Prefetch #

One-to-One Backward Relationships #

Q expressions #

F expressions #

Caches #

SQL to Django #

General #