![](/img/trans.png)
[英]Django Model Inheritance (is there a way to combine two different models)
[英]Is there a way in Django to combine two queries of a single model with different parameters?
我希望能够显示一个表,其中存储了当前值以及去年的值。 现在,我查询所有商店,然后遍历每个商店并从比较日期和时间获取值。 但这最终需要60多个查询。
这是我的模特。 所有数据都保存在ShowroomData模型中
class Stores(models.Model):
storeid = models.IntegerField(default=0, primary_key=True)
location = models.CharField(max_length=128)
class ShowroomData(models.Model):
store = models.ForeignKey(Stores, db_column="storeid", default=0, on_delete=models.CASCADE)
date = models.DateField(db_index = True) # Field name made lowercase.
time = models.IntegerField() # Field name made lowercase.
sales = models.DecimalField(max_digits=10, decimal_places=2) # Field name made lowercase.
tax = models.DecimalField(max_digits=10, decimal_places=2) # Field name made lowercase.
我的views.py
for store in current_data:
comparison_data = ShowroomData.objects.filter(store=self.store, date=comparison_date, time=self.time)
if comparison_data:
for record in comparison_data:
store.compare_amount = record.sales + record.tax
我希望能够将所有这些存储在一个查询集中,然后在模板中对其进行循环,而不必在一开始就进行循环以重新追加查询。 是否有可能将第二个查询的数据放在查询集中的单独字段中? 谢谢!
聚合可能是一个非常简单的解决方案。
annotate()用于创建每个对象的摘要,而F对象(用于您的情况)用于对两个字段求和。
ShowroomData.objects.annotate(compare_amount=F('sales')+F('tax')).filter(store=self.store, date=comparison_date, time=self.time))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.