python - Django poor performance when annotating on multiple related fields -


i've run performance problem 1 of django views.

i use models resemble these example models:

class user(models.model):     name = models.charfield(max_length=32)  class post(models.model):     author = models.foreignkey('user', related_name='posts')  class comment(models.model):     author = models.foreignkey('user', related_name='comments') 

in view need display how many posts , comments each user has written, , queryset so:

user.objects.annotate(post_count=count('posts', distinct=true),                       comment_count=count('comments', distinct=true)) 

this works expected, performance has become poor increased number of rows in database. have approximately:

users: 1300 comments: 4300 posts: 6200 

and query takes approximately 400ms.

if remove either post_count or comment_count query, execution time drops down acceptable 10ms.

i suspect comes joining table, raises total number of rows 1300 * 4300 * 6200 instead of eg. 1300 * 4300.

but how circumvent problem, best solution store number of comments , posts in database field , make application logic take care of updating when needed?


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -