( Base : if animal.categories sets up a query, which means that the categories are many-to-one with animals, and the default name (category_set) is changed using categories)
It seems to me that your main query should be a category query instead of animals. Let's say you get animals such as:
Animals.objects.filter(name__startswith='A')
You can get categories of these animals with the following query
Category.objects.filter(animal__name__startswith='A')
You can also get animals with this request
Category.objects.filter(animal__name__startswith='A').select_related('category')
But I recommend using separate queries for categories and animals (it will be more efficient, but will make two queries).
Note If you really use one-to-many, you should consider changing it for many-to-many.
source share