通过构建器进行Django复杂查询

时间:2018-11-30 12:21:48

标签: django django-orm query-builder

一段时间以来,我无法使用ORM进行复杂的查询。我知道这是可能的,所以我会原谅。

class Game(models.Model):
    no matter

class Competition(models.Model):
    game = models.ForeignKey(to='game.Game', verbose_name=_('game'), related_name='competitions',
                         on_delete=models.PROTECT)

class User(models.Mode):
    no matter

class Balance(models.Model):
    user = models.OneToOneField(to=User, on_delete=models.CASCADE, primary_key=True)

class BalanceTransaction(models.Model):
    TYPES = (
        (TYPE_COMMISSION, _('commission')),
    }
    competition = models.ForeignKey(to='competition.Competition', verbose_name=_('competition'), related_name='transactions', on_delete=models.CASCADE, null=True, blank=True)
    balance = models.ForeignKey(to=Balance, on_delete=models.CASCADE, related_name='transactions')
    amount = models.DecimalField(_('Transaction amount'), default='0.0', max_digits=28, decimal_places=18,
                             null=False, blank=False)

    type = models.CharField(_('type'), max_length=10, default=TYPE_DEPOSIT, choices=TYPES, null=False, blank=False

我必须返回一个游戏查询集,其中每个元素将具有一个额外的“收入”字段,该字段存储该游戏的所有交易类型为“佣金”的总和

    Game.objects.filter(publisher__owner=self.request.user.pk).annotate(
    income=Sum(Case(
        When(
            Q(publisher__owner__balance__transactions__type=BalanceTransaction.TYPE_COMMISSION),
            then=???,
        )
    ))

似乎这种方式是不可能的,我必须使用子查询,但到目前为止我还没有成功。

1 个答案:

答案 0 :(得分:0)

我认为您不需要子查询或大小写,只需要一个标准过滤器即可。

Game.objects.filter(publisher__owner=self.request.user.pk).filter(
    publisher__owner__balance__transactions__type=BalanceTransaction.TYPE_COMMISSION
).annotate(
    income=Sum('publisher__owner__balance__transactions__amount)
)

请参阅order of annotate and filter clauses,以了解其工作原理。