【问题标题】:django - specific query or calculation for this relationshipsdjango - 此关系的特定查询或计算
【发布时间】:2019-12-26 11:35:00
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: python django django-models django-orm


    【解决方案1】:

    试试这个查询集:

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

    【讨论】:

      猜你喜欢
      • 2016-11-14
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多