我正在尝试使用过滤器方法来检查我的Place(模型在下面)是否现在打开。我定义了字段open_hours和close_hours。算法对我来说看起来不错(第一个条件适用于21:00-23:00小时,第二个条件适用于21:00-01:00),但是由于我对Q和F对象有新的了解,因此我遇到了语法错误。
第81行 Q(营业时间__lt =当前时间)&Q(营业时间__gt =当前时间)) ^ SyntaxError:位置参数紧跟关键字参数
class Place(models.Model):
name = models.CharField(max_length=50)
lat = models.FloatField()
lng = models.FloatField()
address = models.CharField(max_length=50)
district = models.CharField(max_length=50, choices=DISTRICTS)
link = models.URLField(help_text="www.websiteurl.pl")
open_hours = models.TimeField()
close_hours = models.TimeField()
week_day = MultiSelectField(choices=DAYS)
additionalInfo = models.CharField(max_length=500, blank=True, null=True)
def __str__(self):
return self.name
def hasToBeOpenedRightNowFilter(self, queryset, name, value):
now = datetime.datetime.now()
current_day = now.strftime("%A") #current_day
current_time = now.time() #current_time
queryset_day = queryset.filter(week_day__contains = current_day) #queryset filtered after day
query_time_1 = queryset.filter(open_hours__lt = F('close_hours'), #queryset filtered after first condition
Q(open_hours__lt = current_time) & Q(close_hours__gt = current_time))
query_time_2 = queryset.filter(open_hours__gt = F('close_hours'), #queryset filtered after second condition
Q(open_hours__lt = current_time) | Q(close_hours__gt = current_time))
queryset_time = query_time_1 | query_time_2 #merge two querysets with time conditions
queryset_true = queryset_time & queryset_day #merge queryset with filter after day
if not value:
queryset = queryset.exclude(id__in=queryset_true.values('id'))
return queryset
return queryset_true
答案 0 :(得分:0)
您需要将Q对象放在.filter
query_time_1 = queryset.filter(Q(open_hours__lt = current_time) & Q(close_hours__gt = current_time), open_hours__lt = F('close_hours'))