TIL: QuerySet.filter()

July 30, 2023

tags: #python, #django, #documentation, #TIL


Chaining a .filter() to a Django QuerySet will return a new QuerySet. It does not modify in-place the existing query.

For example, I was doing this:

queryset.filter(user=self.request.user.id)
queryset.filter(book__slug_full=self.kwargs.get("book"))

when I should have been doing this:

queryset = queryset.filter(user=self.request.user.id)
queryset = queryset.filter(book__slug_full=self.kwargs.get("book"))

This is not unique. According to the docs, this is true for most QuerySet methods.