Django 如何在基于类的视图中过滤多个查询?
我有以下型号:Django 如何在基于类的视图中过滤多个查询?,django,django-models,django-templates,Django,Django Models,Django Templates,我有以下型号: class List(models.Model): participants = models.ManyToManyField(Participant, through='ParticipantThroughModel', blank=True) class ParticipantThroughModel(models.Model): participantlist = models.ForeignKey(List, null=True, on_delete=m
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)
我有以下看法:
class ListDetail(DetailView):
model = List
template_name = 'participantlists/participantlist_detail.html'
context_object_name = 'participantlist
在我的模板中,我可以通过以下方式显示所有参与者
:
{% for obj in participantlist.participantthroughmodel_set.all %}
{{ obj.participants }}
{% endfor %}
但是,如果我想过滤此代码以显示包含所有
参与者的此代码
和另一个for
循环,仅显示参与者
以及is\u responsible\u person=True
如何执行此操作?您可以在视图中过滤查询集,方法是覆盖:
在模板中,您可以迭代参与者
:
{% for obj in participants %}
{{ obj.participants }}
{% endfor %}
{%for obj in participants%}
{{obj.participants}}
{%endfor%}
谢谢,如果我还想传递未过滤的原始参与者列表
我如何更新此内容?@alias51:您只需在结果
(这是一个简单的字典)中添加一个额外的项即可。@alias51参与者列表
仍在您的上下文中,在参与者
(结果)旁边['participantlist']
由对super()的调用填充。获取上下文数据()
)
{% for obj in participants %}
{{ obj.participants }}
{% endfor %}