Issue
I have the following models:
class List(models.Model):
participants = models.ManyToManyField(Participant, through='ParticipantThroughModel', blank=True)
class ParticipantThroughModel(models.Model):
participantlist = models.ForeignKey(List, null=True, on_delete=models.PROTECT)
participants = models.ForeignKey(Participant, null=True, on_delete=models.PROTECT)
is_responsible_person = models.BooleanField()
class Participant(models.Model):
username = models.CharField(max_length=255)
And I have the following view:
class ListDetail(DetailView):
model = List
template_name = 'participantlists/participantlist_detail.html'
context_object_name = 'participantlist
In my template, I can display all the Participant
via:
{% for obj in participantlist.participantthroughmodel_set.all %}
{{ obj.participants }}
{% endfor %}
However, if I want to filter this to display both this code with all participants
and another for
loop showing only participants
with is_responsible_person = True
how can I do this?
Solution
You can filter the queryset in the view, by overriding the get_context_data(…)
method [Django-doc]:
class ListDetail(DetailView):
model = List
template_name = 'participantlists/participantlist_detail.html'
context_object_name = 'participantlist'
def get_context_data(self, **kwargs):
result = super().get_context_data()
result.update(
participants=self.object.participantthroughmodel_set.filter(is_responsible_person=True)
)
return result
in the template, you then can iterate over participants
:
{% for obj in participants %}
{{ obj.participants }}
{% endfor %}
Answered By - Willem Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.