我有以下型号:
class Announcement(models.Model):
name = models.CharField(max_length=500)
content = models.CharField(max_length=1000)
is_active = models.BooleanField(default=False)
date_start = models.DateTimeField()
date_end = models.DateTimeField()
def __str__(self):
return self.name
我可以过滤is_active
字段上的对象,例如:
def announcements(request):
announcements = Announcement.objects.all().filter(
is_active = True
)
return HttpResponse(
serializers.serialize("json", announcements))
这很好用。但是,当我想根据date_start
字段过滤它们时,这样:
def announcements(request):
announcements = Announcement.objects.all().filter(
date_start >= datetime.now()
)
return HttpResponse(
serializers.serialize("json", announcements))
我收到global name 'date_start' is not defined
错误。
答案 0 :(得分:4)
您需要使用queryset过滤器查找__gte (greater than or equal):
announcements = Announcement.objects.all().filter(date_start__gte = datetime.now())
答案 1 :(得分:3)
这种语法错误:
announcements = Announcement.objects.all().filter(date_start >= datetime.now())
filter
需要Python关键字参数。所以实际上你可以:
announcements = Announcement.objects.all().filter(date_start__gte=datetime.now())