django - 这种关系的特定查询或计算

django - specific query or calculation for this relationships

我的模型中有 InfluencerInfluencerList classes(多对多关系)。 InfluencerList 模型也与 User 模型存在多对一关系。我有这个查询,它查看登录用户的 InfluencerList 并计算每个列表中的影响者,它工作正常。

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

我还想在每个 InfluencerList 中传递总关注者数量(Influencer class 中的一个字段)。我想我必须使用类似的东西,但我不知道在哪里分配查询结果,因为有很多列表:

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

最清楚最好的方法是什么?

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

试试这个查询集:

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