我在django有这样的模特:
class Client(models.Model):
type = (choices)
class Bill(models.Model):
client = models.ForeignKey(Client)
class Detail(models.Model):
total = models.MoneyField() # i used currency package
bill = models.ForeignKey(Bill)
详细信息类包含Bill的销售详细信息,我已经在Bill.save()方法中同时保存了账单和详细信息,但我想将Client.type从Bill.save()传递给Detail。保存(),我想要那样的东西
def save(self, *args, **kwargs): #this is Bill save method
client = self.Client
transaction.atomic:
super(Bill, self).save(*args, **kwargs)
for detail in self.details
detail.save(client)
def save(self, *args, **kwargs): #this is Detail save method
self.pricing(client)
super(Detail, self).save(*args, **kwargs)
def pricing(self, client):
if client.type = 'value1':
self.total = self.total - (self.total*5/100)
elif client.type = 'value2':
self.total = self.total - (self.total*7/100)
else:
self.total = self.total - (self.total*10/100)
我不知道传递参数如何在python和Django上运行,解决这个问题的最简洁的解决方案是什么?总之,我希望bill.save方法选择client.type值并通过detail.save传递它来计算总数和案例。
由于
答案 0 :(得分:1)
您可以使用save方法在kwargs中传递参数尝试使用以下代码在另一个保存方法中传递客户端变量(detail.save(client=client)
)并使用client = kwargs.get('client')
def save(self, *args, **kwargs): #this is Bill save method
client = self.Client
transaction.atomic:
super(Bill, self).save(*args, **kwargs)
for detail in self.details
detail.save(client=client)
def save(self, *args, **kwargs): #this is Detail save method
client = kwargs.get('client')
self.pricing(client)
super(Detail, self).save(*args, **kwargs)
这可能对你有帮助..
答案 1 :(得分:1)
在您的情况下,您可以简单地使用自我属性:
def save(self, *args, **kwargs): #this is Detail save method
self.pricing(self.bill.client)
# ^^^^^^^^^^^
super(Detail, self).save(*args, **kwargs)