Tuesday, September 24, 2019

Re: how to use django pagination with sql query and not ORM

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%



On Wed, 25 Sep 2019 at 00:47, leb dev <testdevleb@gmail.com> wrote:
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.



--
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+unsubscribe@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.

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAEMqiPc5zqcT%2BaPYSySLCJe22nPC-fCk_RkaTvWvRx5CSqkXQA%40mail.gmail.com.

No comments:

Post a Comment