我有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
每个Streamer都连接了多个帐户。
每个帐户可以有多个流。
每个流都有一个分数。
现在让我们说,对于每个Streamer,我想为连接到该Streamer的每个帐户的每个流添加总分。
我会做的:
from django.db.models import Sum
Streamer.objects.annotate(total_score=Sum('account__stream__score'))
如果我想按总分对每个彩带进行订购,我会这样做:
streamers = Streamer.objects.annotate(total_score=Sum('account_stream__score')).order_by('total_score')
我现在想做的是按相同的分数过滤流光列表,但仅从已连接Instagram平台的帐户中过滤。
我不确定如何执行此操作,但我认为可能是这样的(不是实际的工作代码):
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')
我一直在寻找与此相关的东西,但找不到答案。
它需要被彩带过滤。
同样,该想法是由Streamers进行总分过滤,但只能从与Streamer的instagram帐户连接的Streams中提取得分。
希望这是有道理的。
谢谢!
答案 0 :(得分:2)
您可以尝试这样(通过在注释上使用filter
)
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')