Wednesday, May 31, 2017

Re: count from multiple tables in a single query?

If I want to get the total count from both tables it can be done like this,

author_count = Author.objects.count()
= Publisher.objects.count()

My concern is that this results in two different queries to the database. Can it be done with a single query call?

Probably not with the standard ORM and the model setup you provided with no relation between the tables. You'll likely have to drop down to raw SQL. I'd do testing. I doubt you'll have much of a performance gain by combining the two queries in to one since you are just doing a count and both tables have unique indexes, aside from saving the overhead of one SQL call (not the actual query itself). Two calls would keep the code simple and portable, which to me is more important than a marginal gain in performance.


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
To post to this group, send email to
Visit this group at
To view this discussion on the web visit
For more options, visit

No comments:

Post a Comment