user3614681
user3614681

Reputation:

How to filter records from a model within view?

I have a MyTab table in the model file as below:

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

And a view file as below:

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)

How to rewrite my index() method to return only required records? I tried below options but I am not getting the right syntax. Thanks for any help.

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

Upvotes: 1

Views: 45

Answers (1)

Rod Xavier
Rod Xavier

Reputation: 4043

Try this

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

For more info, please read Django's Queryset API reference.

Upvotes: 1

Related Questions