Search code examples
pythondjangodjango-modelsdjango-database

django display five objects from database


So I just try to build an app in Python Django and I try to display a certain quantity of objects, for example I want to take from the database just first five objects and display it. Another next five objects display on another site and another five objects display on the next site and so on... .How can I do that? I now that I can do for example: mountains = peaks.objects.all() and then with for loop in template display all of objects. But I want just five per site.


Solution

  • You can use generic views for these. Like these

    from django.views.generic import ListView
    from .models import Peak
    
    class MountainList(ListView):
        model = Peak
        paginate_by = 5
    

    In your urls.py you should have a pattern like these

    from .models import MountainList
    
    urlpatterns = [
        ...
        path('mountains/',MountainList.as_view(),name='mountain_list'),
        ...
    ]