Django:注释过滤的反向关系 [英] Django: Annotate a filtered reverse relationship

查看:38
本文介绍了Django:注释过滤的反向关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4种型号:

class Platform(models.Model):
    name = models.CharField(max_length=10)

class Streamer(models.Model):
    name = models.CharField(max_length=50)

class Account(models.Model):
    name = models.CharField(max_length=50)
    streamer = models.ForeignKey(Streamer, on_delete=models.CASCADE)
    platform = models.ForeignKey(Platform, on_delete=models.CASCADE)

class Stream(models.Model):
    host = models.ForeignKey(Account, on_delete=models.CASCADE)
    score = models.PositiveIntegerField(default=0)

共有3个平台:Instagram,Twitch和YouTube

There are 3 Platforms: Instagram, Twitch, and YouTube

每个Streamer都连接了多个帐户.

Each Streamer has multiple accounts connected to it.

每个帐户可以有多个流.

Each account can have multiple streams.

每个流都有一个分数.

现在让我们说,对于每个Streamer,我想为连接到该Streamer的每个帐户的每个流添加总分.

Now lets say that for each Streamer I want to add a total score for every stream connected to every account connected to that Streamer.

我会做的:

from django.db.models import Sum

Streamer.objects.annotate(total_score=Sum('account__stream__score'))

如果我想按总分对每个彩带进行订购,我会这样做:

If I wanted to order each streamer by the total score I would do:

streamers = Streamer.objects.annotate(total_score=Sum('account_stream__score')).order_by('total_score')

我现在想做的是按相同的分数过滤流光列表,但仅从已连接Instagram平台的帐户中过滤.

What I'd like to do is now filter a list of Streamers by the same score but only from Accounts that have the Instagram Platform connected to it.

我不确定如何执行此操作,但我认为可能是这样的(不是实际的工作代码):

I'm not sure how to do this, but I would think it'd be something like this (not actual working code):

instagram_top_streamers_list = Streamer.objects.annotate(total_score_instagram=Sum(
    # Somehow filter the account
    'account__platform__name="Instagram"

    # Then calculate the score for that one
    'account__stream__score')).order_by('-total_instagram_score')

我一直在寻找与此相关的东西,但找不到答案.

I've been looking for something related to this for hours but couldn't find an answer.

它需要被彩带过滤.

同样,该想法是由Streamers进行总分过滤,但只能从连接到Streamer instagram帐户的Streams中提取得分.

Again, the idea is to do the total score filter by Streamers but ONLY pull the score from Streams that are connected to a Streamer's instagram Accounts.

希望这是有道理的.

提前谢谢!

推荐答案

您可以尝试这样(通过使用

You can try like this(by using filter on annotation):

from django.db.models import Sum, Q

instagram_top_streamers_list = Streamer.objects.annotate(
    total_score_instagram=Sum(
        'account__stream__score',
        filter=Q(account__platform__name='instagram'))
    ).order_by('-total_score_instagram')

这篇关于Django:注释过滤的反向关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆