我需要在每个记录中对两个字段求和,然后如果该总和大于0,则选择记录。 这是模型的样子:
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)
这是我建立的查询
Location.objects.extra(select={'fieldsum': 'day1 + day2+ day3+ day4+ day5+ day6+ day7'},where=['fieldsum > 0'])
但它会抛出错误
django.db.utils.ProgrammingError: column "fieldsum" does not exist
答案 0 :(得分:3)
您不需要添加额外字段,只需使用F() Django built-in function并转换
即可 day1 + day2+ day3+ day4+ day5+ day6+ day7 > 0
至day1 > 0 - day2 - day3 - day4 - day5 - day6 - day7
然后,您的查询应如下所示:
Location.objects.filter(day1__gt = 0 - F('day2') - F('day3') ..... -F('day7') )