在Django应用程序中,我每天都会在这样的模型中保留几十位用户:
File storagefileindex = new File(zipInputList.get(i));
我想知道用户的分数与结果日相比发生了巨大变化的日子。也就是说,例如,如果用户得分比前一天高10倍。
如何在使用Django ORM的查询过滤器中包含这样的条件?是否可以使用如下所述的条件表达式进行单个查询:https://docs.djangoproject.com/en/1.9/ref/models/conditional-expressions/
感谢。
答案 0 :(得分:1)
如果您稍微更改您的分数类别以包括前一天的分数(这无疑是非常浪费),您可以使用F expressions将查询打包到一行。
你的新班级:
class Score(models.Model):
user = models.ForeignKey(User)
score = models.PositiveIntegerField(default=0)
lastscore = models.PositiveIntegerField(default=0)
date = models.DateField(auto_now_add=True)
然后过滤器变为:
from django.db.models import F
daily_chg = 10
big_changes = Score.objects.filter(score__gt=daily_chg*F('lastscore'))
我没有使用timedeltas来搜索和设置前一天的得分字段,而是look into通过Meta类建立排序并在保存当天得分时调用latest()
。
答案 1 :(得分:0)
使用from my_app.models import Score
import datetime
def some_view(request):
days_with_score_boost = []
today = datetime.date.today()
for each_day in xrange(0,7):
day_to_test, day_before_to_test = today - datetime.timedelta(days=each_day), today - datetime.timedelta(days=each_day + 1)
day_before_score = Score.objects.get(user=request.user,date=today - datetime.timedelta(days=each_day)).score # will need to catch the exception raised if .get return None and process appropriately
if Score.objects.filter(user=request.user,score__gte=days_before_score * 10,date=day_before_to_test).count() > 0:
days_with_score_boost.append(day_to_test)
我们可以针对特定用户测试上周的日期:
days_with_score_boost
auto_now_add
将是datetime.date对象的列表,其中得分从前一天增加10或更多。
在回复您的评论时,我会制定一项措施,在保存时检查分数是否已经提升。但是,我会放弃from django.utils import timezone
from django.core.exceptions import ObjectDoesNotExist
class Score(models.Model):
user = models.ForeignKey(User)
score = models.PositiveIntegerField(default=0)
date = models.DateField(null=True,blank=True)
increased_ten_over_previous_day = models.BooleanField(null=True,blank=True)
def save(self, *args, **kwargs):
self.date = timezone.now().today()
try:
yesterday_score = Score.objects.get(date=self.date-timezone.timedelta(days=1)).score
self.increased_ten_over_previous_day = (yesterday_score * 10) <= self.score
except ObjectDoesNotExist: # called if Score.object.get returns no object; requires you only have one score per user per date
self.increased_ten_over_previous_day = False
super(self, Score).save(*args, **kwargs)
而转而选择保存方法。
increased_ten_over_previous_day
然后,您可以过滤True
stylo
为server.R
的对象。