Wednesday, 15 February 2012

How to save foreign key referenced model instance when parent model instance is created in Django -



How to save foreign key referenced model instance when parent model instance is created in Django -

i have 2 model packet , transaction. , transaction has many-to-one relationship packet. want create first transaction when packet created.

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 none: 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() homecoming super(packet, self).save(*args, **kwargs)

how create transaction instance when packet instance created first transaction automatically added when new packet created.

you need create packet object (ie. calling super() method) before creating transaction. way can provide right packet object transaction creates.

if self.pk none: 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() homecoming

django django-models

No comments:

Post a Comment