2012-07-13 6 views
19
class PO(models.Model) 
    qty = models.IntegerField(null=True) 
    cost = models.IntegerField(null=True) 
    total = qty * cost 

위의 total = qty * cost은 어떻게 해결할 수 있습니까? 나는 그것이 오류를 일으킬 것이라는 것을 안다. 그러나 이것을 다루는 방법을 모른다.값이 다른 필드 값의 계산 인 필드 만들기

답변

12

Justin Hamades answer

class PO(models.Model) 
    qty = models.IntegerField(null=True) 
    cost = models.IntegerField(null=True) 

    @property 
    def total(self): 
     return self.qty * self.cost 
+1

@ ahsan의 대답이 정확히 무엇입니까? – Ahsan

+0

total은 속성이 아니기 때문에 미묘하게 잘못되었습니다. – datashaman

+3

@MarlinForbes 'total = property (_get_total) same'을'@ property'와 isnt하지 않습니까? [여기] (http://www.artima.com/weblogs/viewpost.jsp?thread=240808)를 확인하십시오. – agconti

35

당신은 totalproperty 필드를 만들 수 있습니다 참조 docs

class PO(models.Model) 
    qty = models.IntegerField(null=True) 
    cost = models.IntegerField(null=True) 

    def _get_total(self): 
     "Returns the total" 
     return self.qty * self.cost 
    total = property(_get_total) 
+0

우리는 수량과 비용의 계산으로 그것을 만들 수있는 방법이 있나요? – rechie

+0

'total'은 필드처럼 동작합니다. 다른 필드와 마찬가지로 클래스 객체를 통해 액세스 할 수 있습니다. – Ahsan

+0

@Secator .. 고마워! – rechie