简体   繁体   中英

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.

Here are my models. All of the data lives in the ShowroomData model

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

    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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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