我有三个模型Flat
,FlatDebit
和FlatDebitType
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 []>
抱歉我的英语不好。