Wednesday, May 31, 2017

Re: count from multiple tables in a single query?

Hello James/Matthew,

I was afraid to hear that. The models are unrelated and I do not want to take the trouble of dropping out of the ORM. Since it's a web-service I'm building, a work-around is to cache results, but I was challenged to find a single DB call solution and wanted to be sure that it wouldn't be possible with the ORM.

Thanks for replying!

Looking into caches,
Abraham V.


On Wednesday, 31 May 2017 16:31:04 UTC-4, Matthew Pava wrote:

Hi Abraham,

If the models are related, you can use double underscore notation with the Count aggregate function.

If the models are unrelated, then I'm fairly certain that you can only use separate queries to get your results.

 

 

From: 'Abraham Varricatt' via Django users [mailto:django...@googlegroups.com]
Sent: Wednesday, May 31, 2017 2:14 PM
To: Django users
Subject: count from multiple tables in a single query?

 

Hello,

Is it possible to get the count of entries from multiple tables in a single query call? I'm looking at the official docs on aggregation and I can't find anything. For example assume I have the following 2 tables,

class Author(models.Model):
    name
= models.CharField(max_length=100)
    age
= models.IntegerField()

class Publisher(models.Model):
    name
= models.CharField(max_length=300)
    num_awards
= models.IntegerField()


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?


Yours,
Abraham V.

--
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...@googlegroups.com.
To post to this group, send email to djang...@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/5ffdbc1a-fb84-4bff-a711-eaad77c3ae15%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
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/7b99f473-0ea3-4d0a-acd2-08b05c96d687%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment