Django条件注释:如果`When`条件返回空,则Queryset返回空

时间:2017-07-19 10:22:46

标签: django

我有三个模型FlatFlatDebitFlatDebitType

class Flat(models.Model):
    number = models.IntegerField()


class FlatDebit(models.Model):
    flat = models.ForeingKey('foo.Flat', related_name='debits') 
    debit_type = models.ForeingKey('foo.FlatDebitType') 
    unpaid_amount = models.DecimalField()

class FlatDebitType(models.Model):
    TYPE1 = 1
    TYPE2 = 2
    TYPE_CHOICES = ((TYPE1, 'Type 1'), (TYPE2, 'Type 2'),)
    type = models.PositiveSmallIntegerField(default=TYPE1, choices=TYPE_CHOICES)

我想通过unpaid_amount获得每个单位的部分借记debit_type的总和。 如果存在FlatDebitType具有TYPE2的借记,则注释后按预期工作。

flats = Flat.objects.all()
# <QuerySet [<Flat: 1>,..]

flats = flats.annotate(
    # type1_unpaid_amount=Sum(....),
    type2_unpaid_amount=Sum(Case(

        # If there is no debit which has debit_type=TYPE2
        # `flats` queryset return empty
        When(debits__debit_type__type=FlatDebitType.TYPE2, 
            then='debits__unpaid_amount'
        ),
        output_field=models.DecimalField(), 

        # I specified default value for getting 0 as value
        # if debits with TYPE1 but not affecting
        default=Decimal('0.00')
    )),
)

但是如果没有指定debit_type的借方,则queryset返回空。

print(flats)
#<QuerySet []>

抱歉我的英语不好。

0 个答案:

没有答案