如何解决在Django模板中过滤反向查询
我有一个看起来像这样的模型
class Invoice(models.Model):
inv_number = models.CharField(max_length=10,primary_key=True)
customer = models.ForeignKey(Customer,on_delete=models.PROTECT)
inv_date = models.DateField()
class Txn(models.Model):
invoice = models.ForeignKey(Invoice,on_delete=models.PROTECT)
transaction_date = models.DateField()
reference = models.CharField(max_length=12)
amt = models.IntegerField()
我想在我的模板中显示一个报告,其中列出了已过滤的发票,每个报告都有一个已过滤交易的子列表。
在我看来,我已经执行了以下操作:
invoice_list = Invoice.objects.filter(customer=customer)
我将其传递到模板中。在模板中,我执行以下操作:
{% for invoice in invoice_list %}
{{ invoice.inv_number }},{{ invoice.customer}},{{ invoice.inv_date }}
{% for txn in invoice.txn_set.all %}
{{ txn.transaction_date }},{{ txn.reference }},{{ txn.amt }}
{% endfor %}
{% endfor %}
这非常有用,可以显示每个过滤的发票的整个交易清单。问题是,如何同时过滤模板中每张发票的交易列表-如果我只想要某个日期范围内的交易或匹配特定参考的交易怎么办?
在将主查询集放入上下文之前,是否可以将视图中的每个发票的过滤器传递给视图中的每个发票的txn_set查询集?感谢您的任何答复!
解决方法
建议:在视图中而不是在模板中收集发票和交易。
使用此查看代码,您可以将查询数量减少到1,因此比您的代码(查询每个发票的Txn
表)要好得多:
# build basic query
qs = Txn.objects.select_related('invoice')\
.filter(invoice__customer=customer)\
.order_by('transaction_date')
# add filtering; here is an example,but it could be with date filter as well
reference = request.GET.get('reference','')
if len(reference) > 0:
qs = qs.filter(reference__icontains=reference)
invoice_dict = {}
for txn in qs:
# add the Invoice if it does not exist yet
if txn.invoice_id not in invoice_dict:
invoice_dict[txn.invoice_id] = {
'invoice': txn.invoice,'txn_list': [],}
# add the Txn
invoice_dict[txn.invoice_id]['txn_list'].append(txn)
# sort by Invoice date
invoice_data_list = sorted(
invoice_dict.values(),key=lambda x: x['invoice'].inv_date)
然后在您的模板中:
{% for elem in invoice_data_list %}
{{ elem.invoice.inv_number }}
{{ elem.invoice.customer}}
{{ elem.invoice.inv_date }}
{% for txn in elem.txn_list %}
{{ txn.transaction_date }}
{{ txn.reference }}
{{ txn.amt }}
{% endfor %}
{% endfor %}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。