如何在datetime字段上过滤对象?

时间:2015-07-03 08:58:56

标签: python django python-2.7

我有以下型号:

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错误。

2 个答案:

答案 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())

有关Django docs: Making queries: Field lookups的详情。