I had a many-to-many relationship between two Django Models:
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
...
bees = models.ManyToManyField('Bee')
class Bee(models.Model):
...
in my template, I want to have a different output depending on whether the user has certain Bees. What I’m doing right now is to create a custom filter that does something resembling this:
@register.filter
def my_filter(user, bee):
userprofile = user.get_profile()
return bee in userprofile.bees.all()
and in the template, I can use it as such:
{% for bee in bees %}
{% if user|my_filter:bee %}
I am in {{ bee }}
{% else %}
I am not in {{ bee }}
{% endif %}
{% endfor %}
but this seems hackish since 1) I called .all() — loading the all Bees including the bees that I’m not interested in — without using the results, 2) I don’t think I should need to create a custom filter as this should be quite common
What is the proper way to check whether a Model belongs to a many-to-many relationship with another Model?
You could get the list of the user’s bee ids in your view. Something like this:
And then in your template you can do this: