1

The problem is, to get count and table data, I have to hit the database two times in Django. For example:

count = queryset.count() # To get count
data = queryset.values('columns') # To get data

Is there any way to get data in the single query. One solution is to use len() function, but it is not good for a bigger table to load in RAM.

In mysql, I got this, But how to execute through Django ORM

SELECT t1.count, id FROM table1, (select count(*) as count FROM table1) as t1 limit 10;

Any help will be appreciated.

vermanil
  • 212
  • 1
  • 8
  • 1
    Possible duplicate of [django most efficient way to count same field values in a query](https://stackoverflow.com/questions/3606416/django-most-efficient-way-to-count-same-field-values-in-a-query) – floydya Oct 04 '18 at 07:00

1 Answers1

0

I mean len should just count what is already in memory if you get the data first, so it should be better than two queries to database.

data = queryset.values('columns') # To get data
count = len(data) # To get count from database records in memory

Anyway, for direct database queries without the model layer from Django docs:

from django.db import connection

def my_custom_sql(self):
    with connection.cursor() as cursor:
        cursor.execute("SELECT t1.count, id FROM table1, (select count(*) as count FROM table1) as t1 limit 10")
        row = dictfetchall(cursor)

    return row
Sree
  • 350
  • 1
  • 8
  • yes, @stree len() had solved my problem, but It will load all database records in memory which is an issue for a bigger table. – vermanil Oct 04 '18 at 07:12