gpt4 book ai didi

python - 在 for 循环中合并过滤结果

转载 作者:行者123 更新时间:2023-11-30 22:33:19 26 4
gpt4 key购买 nike

我正在使用 Django 制作一个网站。我想组合多个过滤结果(查询集)。

我的模特关系

'工作人员' 1:m '成员(member)' 1:m '付款历史' 1:1 '退款历史'

我的观点.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 >] >

我只想使用具有该对象的查询集,我想要的是模板中的以下查询集:

{% for refund in wanted_history %}
{{ refund.refund_date }}
{{ refund.refund_amount}}
{% endfor %}

如何在 for 循环中传递多个过滤器结果?

最佳答案

您可以使用管道运算符连接查询集:

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)

关于python - 在 for 循环中合并过滤结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45184764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com