python - Django: Get queryset after a certain ID -


i have event model objects sorted event_time (utc unix timestamp) stored django intergerfield in asc order. because i'm not sorting id, creates problem when comes paging, queryset growing. here event model:

# models.py  class event(models.model):     name = models.charfield(max_length=200)     event_time = models.integerfield(default= 0, null=true, blank=true)     created = models.datetimefield(auto_now_add=true) 

now views.py

# views.py      def events_view(request):     # range of queryset sent in request params      last_event_id = int(request.get.get('last_event_id'))     start_time = int(request.get.get('start_time'))     end_time = int(request.get.get('end_time'))      if last_event_id == 0:         queryset = event.objects.filter(event_time__gte = start_time,                          event_time__lte = end_time).order_by('event_time')[:10]      else:         '''this part i'm having trouble with,            when client requests second page,            send same start_time , event_time            before send event id of last             event object first page. need             able next 10 objects in             queryset after event id.'''      return httpresponse(status=200) 

since i'm ordering event_time, need unique page queryset. need make sure when user requests next page don't see same objects we're sent previous page. how can go getting next 10 rows?

just clear, can't use id__gte, lte, gt, lt. queryset not ordered based on id, ordered based on event_time.

you can use django pagination achieve that.

this remove if-else part in code , not need worry last_event_id then. send queryset objects paginator , number of items you’d have on each page, give methods accessing items each page.

to list of objects particular page, send parameter page_no in request.

try this:

from django.core.paginator import paginator  def events_view(request):     # range of queryset sent in request params      start_time = int(request.get.get('start_time'))     end_time = int(request.get.get('end_time'))     page_no = int(request.get.get('page_no', 1))      objects = event.objects.filter(event_time__gte = start_time,                          event_time__lte = end_time).order_by('event_time')     p = paginator(objects, 10)      requested_page = p.page(page_no)     requested_objects_list = requested_page.object_list #  required objects list      return httpresponse(status=200) 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -