如何在视图中过滤模型中的记录?

时间:2014-05-12 14:36:41

标签: python django

我在模型文件中有一个MyTab表,如下所示:

class MyTab(models.Model):
    inserttime = models.DateTimeField(null=False, auto_now=False, auto_now_add=False)
    total_clicks = models.PositiveIntegerField(default=0)

视图文件如下:

def index(request):
    polls_list = Event.objects.all().order_by('-inserttime') # objective is to return records with iserttime > current time and in the order of ascending inserttime
    context = {'polls': polls_list}
    return render(request, 'polls/index.html', context)

如何重写我的index()方法只返回所需的记录?我尝试了下面的选项,但我没有得到正确的语法。谢谢你的帮助。

polls_list = Event.objects.get(inserttime > timezone.now()).order_by('-inserttime')
polls_list = Event.objects.filter(inserttime > timezone.now()).order_by('-inserttime')

1 个答案:

答案 0 :(得分:1)

试试这个

polls_list = Event.objects.filter(inserttime__gt=timezone.now()).order_by('-inserttime')

有关详情,请参阅Django's Queryset API reference