django - specific query or calculation for this relationships

I have Influencer and InfluencerList classes in my model (many-to-many relationship). InfluencerList model has also many-to-one relationship with User model. I have this query which looks in logged in users InfluencerList's and calculates the Influencer's in each list, it works fine.

context['influencer_lists'] = logged_in_user.lists.annotate(influencer_count=Count('influencers'))

I also want to pass the amount of total followers (a field in Influencer class) in each InfluencerList. I think i must use something like that but i don't know where to assign the query results as there are many lists:

q = userList.influencers.annotate(total_followers=Sum('follower_count')) #maybe combined with for userList in logged_in_user.lists.all()

What is the clearest and best way to do it?

models.py:

class Influencer(models.Model):
    fullname = models.CharField('Full Name', max_length = 40, blank=True, null=True)
    follower_count = models.IntegerField('Follower Count', default=None, blank=True, null=True)

class InfluencerList(models.Model):
    name = models.CharField('Name:', max_length=20, blank=False)
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists')
    influencers = models.ManyToManyField('Influencer', related_name='lists') 

views.py:

class InfluencerListsView(LoginRequiredMixin, ListView):
    #model = InfluencerList
    template_name = "app1/influencer_lists.html"
    #context_object_name = "influencer_lists"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        logged_in_user = self.request.user
        context['influencer_lists'] = logged_in_user.lists.annotate(influencer_count=Count('influencers'))

        lists = logged_in_user.lists.all()
        for userList in lists:
            # this line shows the same follower count for each list ofc.
            context["myKey"] = userList.influencers.aggregate(total_followers=Sum('follower_count'))

        return context

Upvotes: 0

Views: 27

Answers (1)

Sergey Pugach
Sergey Pugach

Reputation: 5669

Try this queryset:

logged_in_user.lists.annotate(
    influencer_count=Count('influencers'),
    total_followers=Sum('influencers__follower_count'),
)

Upvotes: 1

Related Questions