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.

1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

yes, @stree len() had solved my problem, but It will load all database records in memory which is an issue for a bigger table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.