Django中有没有一种方法可以将具有不同参数的单个模型的两个查询组合在一起?

时间:2019-01-28 16:05:04

标签: python django mariadb

我希望能够显示一个表,其中存储当前值以及去年的值。现在,我查询所有商店,然后遍历每个商店并从比较日期和时间获取值。但这最终需要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

我希望能够将所有这些存储在一个查询集中,然后在模板中对其进行循环,而不必在一开始就进行循环以重新追加查询。是否有可能将第二个查询的数据放在查询集中的单独字段中?谢谢!

1 个答案:

答案 0 :(得分:0)

aggregation可能是一种非常简单的解决方案。

annotate() 用于创建每个对象的摘要,而 在您的情况下, F 对象用于对两个字段求和。

ShowroomData.objects.annotate(compare_amount=F('sales')+F('tax')).filter(store=self.store, date=comparison_date, time=self.time))