how can I optimise counter using the .annotate() and __gt

all_following_of_10_following = UserFollowing.objects.filter(user__in=random_following_id_list).exclude(following_user= request.user).values_list(
            "following_user", flat=True).order_by('?')
        
    
    final_list = []

    #then we see if a user appears more than once in the list and if they do we get that user and add them to a final suggestion qs
    cnt = Counter(all_following_of_10_following)
    for k, v in cnt.items():
        if (v > 1) and not (UserFollowing.objects.filter(user = request.user, following_user__id = k ).exists()) :
            final_list.append(k)

follow model:

class UserFollowing(models.Model):
    user = models.ForeignKey(
        User,
        related_name="following",
        on_delete=models.CASCADE
    )
    following_user = models.ForeignKey(
        User,
        related_name="followers",
        on_delete=models.CASCADE
    )
    created = models.DateTimeField(auto_now_add=True)

currently:

I am getting a list of all the people random 10 users follow and adding it to a list. if a name appears in that list I added it to the final_list

what I would want to do:

  1. remove the counting, there is no need to count over 2
  2. omit the counting part and do it using annotate and gt
  3. if I can, also get the people who follow that particular person that has been added to this list.

To clarify, you’re trying to get a list (of indeterminate size) of all the people followed by at least 2 of 10 random users?

So is it:

  • pick 10 random users
  • get everyone followed by at least 2 of those 10?

Note: One you have a person on that list, the set of people following that person would be an expression like: found_person.followers.all. That yields the list of UserFollowing objects from which you can use the user field to retrieve the specific users.

pick 10 random users
get everyone followed by at least 2 of those 10?

perfect! yesss

" Note: One you have a person on that list, the set of people following that person would be an expression like: found_person.followers.all . That yields the list of UserFollowing objects from which you can use the user field to retrieve the specific users."

so, in this case I would want the 2 or 3 or 4 or whatever amount of users from the 10 that follow a particular suggested user. that would be a nice to have!