how to use django pagination with sql query and not ORM

401 views
Skip to first unread message

leb dev

unread,
Sep 24, 2019, 3:16:23 PM9/24/19
to Django users
I now how to use django pagination with ORM django after filtering the required data and put in into pagination div

queryset_list = employee.objects.all()
query=request.GET.get("q")
        if query:
            queryset_list=queryset_list.filter(
              Q(name__icontains=query)|
              Q(father_name__icontains=query)|
              Q(mother_name__icontains=query)|
              Q(content__icontains=query)|
              Q(create_date__icontains=query)
              # Q(user__first_name__contains=query)
            ).distinct()


        paginator = Paginator(queryset_list, 5)
        page_request_var = "page"
        page = request.GET.get(page_request_var)
        queryset = paginator.get_page(page)

        context={
            "object_list":queryset,
            "title":"List Items",
            "page_request_var":page_request_var,
        }
        return render(request,"blog/list.html", context)


the above code is working 

my question is how to convert this ORM into raw SQL 

i know that i must use LIMIT and OFFSET  in raw SQL  to embedded into paginator.



Deep Sukhwani

unread,
Sep 24, 2019, 9:09:18 PM9/24/19
to django...@googlegroups.com
Have you tried using the .query on Django's QuerySet (documentation: [1])

For example, if my QuerySet is:
User.objects.filter(username__contains='alpha')

I can obtain the underlying raw SQL Query using:
print(User.objects.filter(username__contains='alpha').query)
>>> print(User.objects.filter(username__contains='alpha').query)
SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `auth_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.`date_joined` FROM `auth_user` WHERE `auth_user`.`username` LIKE BINARY %alpha%



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2d44b204-8520-423a-992c-597fd479f856%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages