我有3个模特
class Lease(CommonInfo):
version = IntegerVersionField( )
#amount = models.DecimalField(max_digits=7, decimal_places=2)
is_renewed = models.BooleanField(default=False)
unit = models.ForeignKey(Unit)
is_terminated = models.BooleanField(default=False)
class LeaseTerm(CommonInfo):
version = IntegerVersionField( )
start_period = models.ForeignKey(Period, related_name='start_period' )
end_period = models.ForeignKey(Period, related_name='end_period')
lease = models.ForeignKey(Lease)
increase = models.DecimalField(max_digits=7, decimal_places=2)
amount = models.DecimalField(max_digits=7, decimal_places=2)
is_terminated = models.BooleanField(default=False)
def clean(self):
model = self.__class__
if self.lease_id and (self.is_terminated == False) and model.objects.filter(lease=self.lease, is_active=True ).count() == 1:
raise ValidationError('!Lease has a active condition already, Terminate prior to creation of new one'.format(self.lease))
class LeasePayment(CommonInfo):
version = IntegerVersionField( )
amount = models.DecimalField(max_digits=7, decimal_places=2)
leaseterm = models.ForeignKey(LeaseTerm)
period_payed_for = models.DateTimeField()
payment_date = models.DateTimeField()
(clean方法只允许一个LeaseTerm处于活动状态而不会终止。)
在我看来,我希望看到为此租约活跃的LeaseTerm所做的所有付款
lease = get_object_or_404(Lease, pk=lease_id)
leaseterm = LeaseTerm.objects.filter(lease=lease, is_terminated =False, is_active = True )
payment = leaseterm.leasepayment_set.all().order_by('payment_date')
但收到错误
'QuerySet'对象没有属性'leasepayment_set'
我做错了什么?
答案 0 :(得分:3)
模型LeaseTerm
的实例具有属性leasepayment_set
,而不是模型LeaseTerm
的查询集。您可以通过获取此类实例来访问leasepayment_set
。
get
代替filter
leaseterm = LeaseTerm.objects.get(lease=lease, ...)
payment = leaseterm.leasepayment_set.all()
循环查询集
leaseterm = LeaseTerm.objects.filter(lease=lease, ...)
for lt in leaseterm: # lt is an instance of LeaseTerm
payment = lt.leasepayment_set.all()
(通过评论更新,感谢Alasdair和Ingomar)从相关模型开始,它更高效,更优雅的查询表达。
LeasePayment.objects.filter(leaseterm__lease=lease)