I need to sum two fields in each record and then if that sum is greater than 0 select the record. Here's what the model looks like:
class Location(models.Model):
day1 = models.IntegerField(default=0)
day2 = models.IntegerField(default=0)
day3 = models.IntegerField(default=0)
day4 = models.IntegerField(default=0)
day5 = models.IntegerField(default=0)
day6 = models.IntegerField(default=0)
day7 = models.IntegerField(default=0)
and this is the query I have built
Location.objects.extra(select={'fieldsum': 'day1 + day2+ day3+ day4+ day5+ day6+ day7'},where=['fieldsum > 0'])
but it throws an error saying
django.db.utils.ProgrammingError: column "fieldsum" does not exist
You dont need add an extra field, just use F() Django built-in function and transform
day1 + day2+ day3+ day4+ day5+ day6+ day7 > 0
to day1 > 0 - day2 - day3 - day4 - day5 - day6 - day7
Then, your query should looks like this:
Location.objects.filter(day1__gt = 0 - F('day2') - F('day3') ..... -F('day7') )
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.