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_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.

-James

--
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2Be%2BciVxVrzLuF7ASWiC34A2MenWvJd3P1GXsP%2Bi-mYQ9FuVvg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment