Unexpected TypeError When Using Django's Fk Field in a Custom QuerySet
I need some guidance on I've tried everything I can think of but I'm optimizing some code but Hey everyone, I'm running into an issue that's driving me crazy. I'm working on a Django project (version 4.0) and have created a custom QuerySet to filter some records based on a foreign key relationship. However, I'm working with a `TypeError` that states: "'NoneType' object is not subscriptable" when I try to access a field from the queryset. Here's what I have so far: First, I have the following models defined: ```python from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE) ``` Next, I created a custom QuerySet for the `Book` model: ```python class BookQuerySet(models.QuerySet): def by_author(self, author_id): return self.filter(author_id=author_id) ``` Then, I am using this QuerySet in my view to get all books by a specific author: ```python from django.shortcuts import render from .models import Book def author_books(request, author_id): books = Book.objects.by_author(author_id) if not books: return render(request, 'no_books.html') return render(request, 'author_books.html', {'books': books}) ``` The `TypeError` is raised when I access `books` in the template like so: ```html {% for book in books %} <h2>{{ book.title }}</h2> {% endfor %} ``` I tried adding debug print statements before the return in `author_books` to check if `books` is returning any results, and it seems to be an empty queryset rather than `None`. However, it shouldn't throw an behavior if it's empty. I also checked the database to ensure there are books associated with the author, and there are indeed records present. Has anyone encountered a similar scenario or knows why I might be getting this `TypeError`? Any advice on how to avoid this would be appreciated! This is part of a larger service I'm building. I'd really appreciate any guidance on this. I recently upgraded to Python LTS. I'm coming from a different tech stack and learning Python. Has anyone dealt with something similar?