I am building a blog site and have models in respect of Category and Posts. Posts have a Many to Many relationship for Category.
class Post(models.Model):
categories = models.ManyToManyField(Category)
Everything is working fine aside from the fact that in the Category list in the template I only want to load categories that actually have posts.
If a category is empty I don't want to display it, I have tried to define a relationship in Category to Post to allow me to use something like {{ if category.posts }}
. At the moment using another Many to Many field in Category is presently giving me an extra field in admin which I don't really want or feel that's needed.
How is best to navigate this relationship, or create one that's suitable?
Cheers Kev
You can use
reverse relations
onManyToMany
fields. In the reverse filter, you must use the related model name (if you did not userelated_name
attribute). So in your question you can use model name as the reverse name like:You can also use this in your filtering functions in views:
Reverse relation name must be lowercase.
Check the documentation here