gpt4 book ai didi

python - 使用 setattr 在模型上设置查询

转载 作者:太空宇宙 更新时间:2023-11-03 18:36:56 25 4
gpt4 key购买 nike

 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

这是引用我之前的问题(该问题已解决)我想要了解的是特定产品从一月到十二月已售出多少型号

到目前为止我已经做到了这一点,我知道这有点粗糙。但如果写得正确的话会对他有帮助:

View .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 %}

最佳答案

您可以进行以下查询:

product = some_product()
year = 2013

product_sells = Sold.objects.filter(product=product, sold_date__year=year)

如果您想知道有多少个人销售这样做:

product_sells.count()

如果您想对产品销售数量求和:

from django.db.models import Sum
product_sells.Sum('model_qty')

一般来说,避免迭代 Products.objects.all(),因为它对数据库和内存的消耗非常大。

关于python - 使用 setattr 在模型上设置查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21382114/

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