Search code examples
djangoreversem2m

how reverse query ManytoMany Django


I have these two models and I want to display the project with a specific task in my page. These are my models:

class Project (models.Model):
    name = models.CharField(verbose_name="Project name", max_length=25)
    tasks = models.ManyToManyField(Task, verbose_name="tasksInProject", blank=True,
                                   related_name="projects+")

class Task(models.Model):
    name = models.CharField(verbose_name="Task", max_length=50)

I call this view:

class TaskToProjectFilterView(DetailView):
    model = Task
    template_name = "vivs/task_filter.html"
    context_object_name = "task_filter"

And this is my html template:

<h4>filter : {{ task_filter }} </h4>
<h4>projects : 
{% for element in task_filter.projects.all %}
    {{ element }} 
{% endfor %}
</h4>

This code displays the {{ task_filter }} but not the list of {{ task_filter.projects.all }}.

Can you help me? I don't understand my mistake. Thanks!


Solution

  • As schwobaseggl stated, remove the + sign and it should work as expected, using:

    {% for element in task_filter.projects.all %}
    

    From the Django Docs:

    If you’d prefer Django not to create a backwards relation, set related_name to '+' or end it with '+'. For example, this will ensure that the User model won’t have a backwards relation to this model: