我正在使用Django建立一个网站。我想结合多个过滤结果(Querysets)。
我模特的关系
'工作人员'1:m'会员'1:m'PaymentHistory'1:1'RefundHistory'
我的view.py:
wanted_refund = set()
for m in staff.members.all():
payment = m.PaymentHistory.filter(division="Membership")
for p in payment:
try:
refund = RefundHistory.objects.filter(payment=p).filter(refund_date__range=[this_month_start, date])
wanted_refund.add(refund)
except RefundHistory.DoesNotExist:
pass
context = {
'wanted_refund' : wanted_refund,}
return render(request, 'refund.html', context)
但是,使用过滤器无效。它只适用于我使用'get'。
print(refund)
向我展示了这样的结果:
< QuerySet [] >
< QuerySet [] >
< QuerySet [] >
< QuerySet [< RefundHistory: RefundHistory object >] >
我想只使用具有该对象的Querysets,我想要的是模板中的下面一个:
{% for refund in wanted_history %}
{{ refund.refund_date }}
{{ refund.refund_amount}}
{% endfor %}
如何将多个过滤器结果传递给for循环?
答案 0 :(得分:2)
您可以使用管道运算符加入查询集:
wanted_refund = RefundHistory.objects.none()
for m in staff.members.all():
payment = m.PaymentHistory.filter(division="Membership")
for p in payment:
try:
wanted_refund |= RefundHistory.objects.filter(payment=p).filter(refund_date__range=[this_month_start, date])
except RefundHistory.DoesNotExist:
pass
wanted_refund = wanted_refund.distinct()
context = {'wanted_refund': wanted_refund}
return render(request, 'refund.html', context)
此外,如果它适合您,您可以使用wanted_refund.update(list(refund))
代替wanted_refund.add(refund)
答案 1 :(得分:1)
使用RefundHistory
的单个查询,可以获得每位会员每次付款的退款记录:
payments = []
for m in staff.members.all():
payments.extend(m.PaymentHistory.filter(division="Membership").values_list('pk', flat=True))
wanted_refund = RefundHistory.objects.filter(payment__pk__in=payments, refund_date__range=[this_month_start, date])
context = {'wanted_refund' : wanted_refund,}
return render(request, 'refund.html', context)