在我的DetailView
内,我有3个非常相似的对象,但所过滤的内容略有不同。
# views.py
def get_context_data(self, **kwargs):
# all sales for all line items (products) with a specified title
sales = Sales.objects.filter(publication__title=self.object)
# filters print sales for a specified title
print_sales = Sales.objects.filter(publicaton__title=self.object, line_item=1)
# filters digital sales for a specified title
digital_sales = Sales.objects.filter(publicaton__title=self.object, line_item=2)
理想情况下,我想显示一个表格,其中所有销售额均按产品和月份分开,如下所示:
| Month | Print Sales | Digital Sales |
| --------------- | ----------- | ------------- |
| January | 2,000 | 3,000 |
| February | 1,000 | 2,000 |
| --------------- | ----------- | ------------- |
| Total: | 3,000 | 5,000 |
| Combined Total: | | 8,000 |
但是,我无法找到一种方法来正确格式化表格并在模板中提供正确的过滤数据。下面的代码段显示格式正确的表格(类似于上面的表格),但每个月都会显示合并的销售数据。
{% for item in sales %}
<tr>
<td>{{ item.issue }}</td>
{% for obj in print_sales %}
<td>{{ obj.net_sales}}</td>
{% endfor %}
{% for obj in digital_sales%}
<td>{{ obj.net_sales}}</td>
{% endfor %}
</tr>
{% endfor %}
##### output ######
| Month | Print Sales | Digital Sales |
| --------------- | ----------- | ------------- |
| January | 3,000 | 5,000 |
| February | 3,000 | 5,000 |
| --------------- | ----------- | ------------- |
| Total: | 3,000 | 5,000 |
| Combined Total: | | 8,000 |
到目前为止,我对模板和标签所做的所有调整都破坏了表格设计。
这是我的模型的缩写版本:
# models.py
class LineItem(models.Model):
name = models.CharField(...) # print sales, digital sales...
...
class Publication(models.Model):
title = models.CharField(...)
...
class Sales(models.Model):
publication = models.ForeignKey(Publication, ...)
issue = models.ForeignKey(Issue, ...) # gets each month from the Issue model
line_item = models.ForeignKey(LineItem, ...)
net_sales = models.DecimalField(...)
...
我可以在模板或视图中进行哪些更改,这将是解决此问题的更好方法?
答案 0 :(得分:0)
您正在使用for循环
{% for item in sales %}
使print_sales和数字销售执行两次。 在这里,他们两个可能都只重现一个对象。 试试这个:
{% for item in sales %}
<tr>
<td>{{ item.issue }}</td>
</tr>
{% endfor %}
{% for obj in print_sales %}
<tr>
<td>{{ obj.net_sales}}</td></tr>
{% endfor %}
{% for obj in digital_sales%}
<tr> <td>{{ obj.net_sales}}</td></tr>
{% endfor %}