[英]Django query chaining multiple filters
This is my schedule object, 这是我的日程表对象,
class Schedule(Base):
tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE, null=True)
first_team = models.ForeignKey(Team, related_name="first_team", on_delete=models.CASCADE, null=True)
second_team = models.ForeignKey(Team, related_name="second_team", on_delete=models.CASCADE, null=True)
first_score = models.IntegerField(default=0, null=True)
second_score = models.IntegerField(default=0, null=True)
sport = models.ForeignKey(Sport, on_delete=models.CASCADE, null=True)
date = models.DateTimeField()
I want to fetch the schedules for a specific sport, for the past 30 days for tournaments which have anything other than a 0.0 bias. 我想获取某项特定运动的时间表,在过去30天中,对于除0.0偏差以外的任何其他比赛。
This is my query 这是我的查询
schedules = Schedule.objects.filter(sport=sport).filter(date__gte=date.today()).filter(
date__lte=(date.today() + timedelta(days=30))).order_by("date").exclude(tournament__bias=0.0)
This doesn't work, can someone help me here. 这行不通,有人可以在这里帮我吗。 Thanks. 谢谢。
Your code is correct way of filtering (although you could merge the two filter()
methods by comma-separating the lookups). 您的代码是正确的过滤方式(尽管您可以通过逗号分隔查找来合并两个filter()
方法)。
The problem might be that you're now filtering for: 问题可能是您正在过滤以下内容:
today() <= date <= today() + 30 days
So if you don't have any instances with a date in the future 30 days (or today), you'll get an empty set. 因此,如果您没有未来30天(或今天)内具有日期的实例,则将获得一个空集。
Just to be sure, you should be using tz.now()
instead of date.today()
, because you probably have USE_TZ = True
(the default value). 可以肯定的是,您应该使用tz.now()
而不是date.today()
,因为您可能具有USE_TZ = True
(默认值)。 See the django docs . 参见django文档 。
Also, you have to invert your date filters, because you are searching for 30 days into the future, not the past. 另外,您必须反转日期过滤器,因为您要搜索的是未来30天而不是过去的30天。
import datetime
from django.utils import timezone as tz
today = tz.localtime(tz.now()).date()
start_date = today - datetime.timedelta(days=30)
end_date = today
schedules = Schedule.objects.exclude(tournament__bias=0.0) \
.filter(sport=sport, date__gte=start_date, date__lte=end_date) \
.order_by("date")
Your chaining filter looks like almost correct but i guess you messing with past 30 days section filtering. 您的链接过滤器看起来几乎是正确的,但是我想您已经对过去30天的部分过滤感到困惑。
schedules = Schedule.objects.filter(sport=sport).filter(date__lt=date.today()).filter(
date__gte=(date.today() - timedelta(days=30))).order_by("date").exclude(tournament__bias=0.0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.