0

I am trying to annotate a count of how many times a Location (a Location model) is followed (a Follow model, using Django Follow), for those Locations that the user is following (hence the filter at the end).

Here is the offending line of code:

following_locations = Follow.objects.annotate(followers_count=Count('target_location__id')).filter(user=user)

But, the resulting followers_count only ever gives me a count of 1 for each item in following_locations (when I loop through it in the template).

Seems simple enough, but not sure where I am going wrong?

1 Answer 1

1

I suspect that if you want a list of locations then you should build a queryset of Location model:

following_locations = Location.objects \
                              .annotate(followers_count=Count('follow')) \
                              .filter(follow__user=user)
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant, this did it, thanks. Interested if it is at all possible using the Follow model, or if I was just barking up the wrong tree. The code that worked in the end: following_locations = Location.objects.annotate(followers_count=Count('follow_location')).filter(follow_location__user=user) (obviously just dependent on my models...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.