[Fixed]-Build a 1toM queryset that sorts for foreignkey

1👍

I suggest you modify the project field on your Task model as follows:

class Task(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE, 
                                related_name='tasks')
    # ...

This will let you access all the tasks for a particular project through project.tasks.all().

You also need to modify your template slightly, because you’re currently referring to projects where you should refer to p, and you need to loop over p.tasks.all not just p.tasks.

{% for p in projects %}
add project html
  {% for t in p.tasks.all %}
    add task html
  {% endfor %}
{% endfor %}

You’ll need to ensure that projects is in the context passed to your template by your view.

👤mjec

Leave a comment