2016-09-25 155 views
1

我有3種型號爲什麼我得到錯誤:'QuerySet'對象沒有屬性?

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() 

(清潔方法只允許一個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' object has no attribute 'leasepayment_set'

我做錯了什麼?

回答

3

模型LeaseTerm的實例具有屬性leasepayment_set,而不是模型LeaseTerm的查詢集。您可以通過獲取像這樣的實例來訪問leasepayment_set

  1. get,而不是filter

    leaseterm = LeaseTerm.objects.get(lease=lease, ...) 
    payment = leaseterm.leasepayment_set.all() 
    
  2. 周圍的查詢集循環

    leaseterm = LeaseTerm.objects.filter(lease=lease, ...) 
    for lt in leaseterm: # lt is an instance of LeaseTerm 
        payment = lt.leasepayment_set.all() 
    
  3. (通過評論更新,感謝麥金太爾和Ingomar)開始與相關的模型,它是更高效和優雅的查詢表達式。

    LeasePayment.objects.filter(leaseterm__lease=lease) 
    
+3

還有第三個選項,可能是在這種情況下有用的:創建一個'LeasePayment'查詢集並使用雙下劃線符號對租賃過濾:'付款= LeasePayment.objects.filter(leaseterm__lease =租賃)' – Alasdair

+1

我建議使用Alasdair給出的選項。如果你有一個大的數據集,這將使用更少的查詢。其實,即使是一個小數據集。但對於大型數據集,性能優勢將顯着;) – hY8vVpf3tyR57Xib

相關問題