1👍
You’re trying to do too much logic in the template. You can’t assign variables as your comment ## Set a flag to 1 ##
suggests.
In your view, create two querysets. One of all the activities, and one for the spectra without an activity.
activities = Activitydiagram.objects.filter(enzymes=enzyme)
spectras_without_activities = Spectraimage.objects.filter(enzymes=enzyme, activity=None)
Then, in your template, loop through the activities, and use the reverse relation to get the related spectra for each activity.
{% for activity in activities %}
{{ activity }}
{% for spectra in activity.spectraimage_set.all %}
{{ spectra }}
{% endfor %}
{% endfor %}
At the end, you can loop through your spectra which do not have a related activity.
{% for spectra in spectras_without_activities %}
{{ spectra }}
{% endfor %}
The code above assumes that spectra.enzyme == activity.enzyme
for every spectra in activity.spectraimage_set.all
. If that’s not the case, you’ll have to add an additional check.
Once you’ve got it working, you optimise the query by using prefetch_related
to fetch the related spectras at the same time as the activities.