简体   繁体   English

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

[英]Is there a way in Django to combine two queries of a single model with different parameters?

I'd like to be able to display a table with a stores current value, as well as the value from last year. 我希望能够显示一个表,其中存储了当前值以及去年的值。 Right now I query all the stores, and then for each store I loop through and get the value from the comparison date and time. 现在,我查询所有商店,然后遍历每个商店并从比较日期和时间获取值。 But this ends up taking 60+ queries. 但这最终需要60多个查询。

Here are my models. 这是我的模特。 All of the data lives in the ShowroomData model 所有数据都保存在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.

My views.py 我的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

I'd like to be able to store all of these in one query set, and then loop over it in the templates instead of having to loop through in the beginning to re append the query. 我希望能够将所有这些存储在一个查询集中,然后在模板中对其进行循环,而不必在一开始就进行循环以重新追加查询。 If at all possible to have the data from the second query in a seperate field in the query set? 是否有可能将第二个查询的数据放在查询集中的单独字段中? Thank you! 谢谢!

A very simple solution is is possible with aggregation . 聚合可能是一个非常简单的解决方案。

annotate() is used to create per-object summaries, while the F object, in your case, is used to sum two fields. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM