1👍
✅
The related query is wrong, but that is not the cause of your error. That is because you need to use a related manager with all()
or filter()
, just like any other manager.
{% for merchant in category.merchants.all %}
Note that this works whether or not you do any special related queries in the view; this syntax is always available, and select_related
does not give access to any more attributes. All it does is make the query more efficient.
However in your case select_related
is not even the correct thing to use; it will have no effect. That’s because it only works for forward relations, and you have reverse relations from Category to Merchant. You need prefetch_related
for that.
categories = Category.objects.prefetch_related('merchants')
Source:stackexchange.com