我有两个模型包和交易。而Transaction与Packet有着多对一的关系。我想在创建数据包时创建第一个Transaction。
def save(self, *args, **kwargs):
"""
:param args:
:param kwargs:
:return:
"""
self.created_on = datetime.datetime.combine(self.created_on.date(),
datetime.datetime.now().time()).replace(tzinfo=utc)
self.updated_on = datetime.datetime.now().replace(tzinfo=utc)
if self.pk is None:
from girvi.models import Transaction
t = Transaction(type='0', description='0',
amount=self.total_worth, packet=self.id,
created_on=self.created_on, updated_on=self.updated_on,
remark='First amount', roi_charged=self.roi_charged,
min_int_period=self.min_int_period)
t.save()
return super(Packet, self).save(*args, **kwargs)
如何在创建Packet实例时创建Transaction实例,以便在创建新Packet时自动添加First Transaction。
答案 0 :(得分:1)
您需要在创建事务之前创建Packet对象(即调用super()
方法)。这样,您就可以为您创建的事务提供正确的Packet对象。
if self.pk is None:
from girvi.models import Transaction
new_packet = super(Packet, self).save(*args, **kwargs)
t = Transaction(type='0', description='0',
amount=self.total_worth, packet=new_packet,
created_on=self.created_on, updated_on=self.updated_on,
remark='First amount', roi_charged=self.roi_charged,
min_int_period=self.min_int_period)
t.save()
return