'Django: Getting the page an object is on

Let's say I have a class Foo. I want to know what page a particular instance of Foo will be on: eg: api.myapp.com/foos/?page=25.

Given an object:

Foo.objects.get(id=500), how can I determine what page my instance will be on?



Solution 1:[1]

My approach is a little bit different so you can do this,

model_ids = (list(Model.objects.values_list('id', flat=True)))

This will give you the list of the ids. After that,

get_page_number = model_ids.index(obj_id) // per_page_objects + 1

If the obj_id is 500 so the index will be 499

now if per_page_objects are 10 then it will give you page number by calculating (499 // 10 +1 = 50). This means your object having an id 500 is on the 50th page.

I hope this will work for you.

Solution 2:[2]

Django by itself does not predefine which url your model will be accessed through. The documentation says - "Django lets you design URLs however you want, with no framework limitations". So the process is rather opposite:

  • you define the url (look inside urls.py) and associate it with the view to be called for processing:

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('foos/', views.foo_list),
        path('foos/<int:id>/', views.foo_detail),
    
  • you should define the views (usually in views.py)

  • and inside the view you can call any models to fetch data from DB

You can implement your API with additional packages like Django Rest Framework. It has Routers that allow you to define a set of urls at once. The following will generate URL patterns like '^foos/$' and '^foos/{pk}/$':

  • you register your url within the router

    from rest_framework import routers
    
    router = routers.SimpleRouter()
    router.register(r'foos', FooViewSet)
    
  • you should implement FooViewSet and make sure your model is used there.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dharman