1

I used .value('post_id') in django to bring the following values.

<QuerySet [{'post_id': 3}, {'post_id': 2}, {'post_id': 1}, {'post_id': 3}]>

If you count the value of each dictionary, you will have one, one, and two, respectively. Which queryset should I look for, instead of counting it as a queryset without for loop ?

models.py

class Like (models.Model) :
    liked_people = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='liked_people', null=True)
leedjango
  • 411
  • 2
  • 9
  • 18

1 Answers1

1

You should annotate the target model, so:

from django.db.models import Count

Post.objects.annotate(
    number_of_liked=Count('liked_people')
)

The Post objects that arise from this will have an extra attribute .number_of_liked that contains the number of related Likeds.

You can further filter the Like objects, for example with:

from django.db.models import Count

Post.objects.filter(
    liked_people__liked_people=my_user
).annotate(
    number_of_liked=Count('liked_people')
)

This will exclude Post objects that have no related Like objects with liked_people=my_user. You can also include these, but then with .number_of_liked = 0, with:

from django.db.models import Count, Q

Post.objects.annotate(
    number_of_liked=Count(
        'liked_people',
        filter=Q(liked_people__liked_people=my_user)
    )
)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555