Home > OS >  Is it possible to use the left join and annotate function in django?
Is it possible to use the left join and annotate function in django?

Time:07-29

# model
class User(AbstractUser):
     pass
class Post(models.Model):
     post = models.CharField(max_length=50)
     user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, blank=True)


# sql
SELECT A.username
      ,COUNT(B.*)
FROM users_user A
LEFT JOIN post B
  ON B.user_id = A.id
GROUP BY A.id

users_user model is default django user model

I want to change query to orm

I tried both "post" and "post_set" using select_related, but I couldn't.

CodePudding user response:

You can .annotate(…) [Django-doc] with:

from django.db.models import Count

User.objects.annotate(num_posts=Count('post'))

The User objects that arise from this QuerySet will have an extra attribute .num_posts.


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

  • Related