How to filter on foreign key properties with Python django?

Estimated read time 1 min read

In Django, you can filter on foreign key properties by using the double underscore (__) syntax to traverse relationships and access related fields. Here’s an example of how to filter on foreign key properties in Django:

Suppose you have two models, Author and Book, where Book has a foreign key relationship with Author. To filter books based on properties of the related author, you can use the double underscore syntax.

from myapp.models import Book

# Filter books based on the author's properties
queryset = Book.objects.filter(author__name='John Doe')

# Access the filtered books
for book in queryset:
    print(book.title)

In this example, assume that the Book model has a foreign key field named author referencing the Author model, and the Author model has a field named name.

To filter the books based on the author’s name, we use the double underscore syntax in the filter() method. The author__name specifies that we want to filter on the name field of the related author.

The resulting queryset will contain only the books where the author’s name matches the specified value (‘John Doe’ in this case).

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply