Можно ли использовать функцию left join и annotate в django?
# 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 является моделью пользователя по умолчанию django
Я хочу изменить запрос на orm
Я пробовал и "post" и "post_set", используя select_related, но не смог.
Вы можете .annotate(…) [Django-doc] с:
from django.db.models import Count
User.objects.annotate(num_posts=Count('post'))
 Объекты User, возникающие в результате этого QuerySet, будут иметь дополнительный атрибут .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 theUsermodel [Django-doc] directly. For more information you can see the referencing theUsermodel section of the documentation.