【发布时间】:2014-02-18 08:46:29
【问题描述】:
class Product(models.Model):
name = models.CharField(max_length=50)
desc = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class ProductModels(models.Model):
product = models.ForeignKey(Product)
name = models.CharField(max_length=50)
price = IntegerField(max_length=50)
def __unicode__(self):
return self.name
class Sold(model.Model)
product = models.ForeignKey(Product)
model_name = models.ForeignKey(ProductModels)
sold_date = models.DateField()
model_qty = models.IntegerField()
def __unicode__(self):
return self.sold_date
这是参考我之前的问题(那个问题解决了)
我想知道的是how many models have been sold from Jan to Dec for the particular product。
到目前为止,我已经这样做了,我知道这有点粗糙。但如果写得正确会对他有帮助:
views.py
allmonths = ['jan' , ....., 'dec']
products = Products.objects.all()
for each_product in products :
models = ProductModels.objects.filter(product = each_product)
for each_model in models:
for months in allmonths :
att_name = str(each_model.model_name) + str(months)
print 'attname %s' % att_name
val = sold.objects.filter(product = each_product ,
model_name = each_model ,(sold_date =(allmonths.indesx(month) + 1))) .aggregate(qty=Sum('model_qty'))
val = temp(val['qty'])
setattr(each_product, att_name , val)
我不确定这是否正确,但这种方法在早期就已经奏效了。我使用了来自here 的getattribute 模板标签。
这就是我的模板的样子:
{% for record in products %}
<tr class="odd gradeX">
<td><span class="label label-warning">{{ record.name }}</span></td>
<td>
<table class="table table-striped table-bordered table-hover" id="pipelineTbl">
{% for model in record.ProductModels_set.all %}
<tr class="odd gradeX">
<td>
<span class="label label-success">{{ model }}</span>
</td>
</tr>
{% endfor %}
</table>
</td>
{% for months in allmonths %}
<td>
<table class="table table-striped table-bordered table-hover" id="pipelineTbl3">
{% for model in record.ProductModels_set.all %}
{% with model|add:months as val %}
<tr>
<td>{{ record|getattribute:val }}</td>
</tr>
{% endwith %}
{% endfor %}
</table>
</td>
{% endfor %}
</tr>
{% endfor %}
【问题讨论】:
-
如果您想知道从 1 月到 12 月销售了多少型号,是否意味着您要计算给定年份销售了多少产品,对吗?
标签: python django django-models django-templates