我有以下型号:
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))
我得到全局名称’date_start’没有定义错误.
最佳答案 您需要使用
queryset过滤器查找,
__gte (greater than or equal):
announcements = Announcement.objects.all().filter(date_start__gte = datetime.now())