I am trying to create some objects of model ABC in from save method of XYZ model, when a XYZ models object is created. See the below code for reference :
Class XYZ(models.Model): name = models.CharField(max_length=150) #Other Feilds def save(self, *args, **kwargs): self.match_tick = self.match_date.timestamp() contest_obj_1 = ContestDetail( contest_of_ABC=self, contest_name="₹1000 Winnnings", filled_status = False, ) contest_obj_1.save() super(MatchDetail, self).save(*args, **kwargs) Class ABC(models.Model): contest_of_ABC = models.ForeignKey(XYZ) contest_name = models.CharField(max_length=100) filled_status = models.BooleanField(default=False)
And here are the error lines :
File "./center/models.py", line 47, in save contest_obj_1.save() File "./center/models.py", line 203, in save super(ContestDetail, self).save(*args, **kwargs) File "/home/FightBack/.virtualenvs/ENV/lib/python3.5/site-packages/django/db/models/base.py", line 762, in save "unsaved related object '%s'." % field.name ValueError: save() prohibited to prevent data loss due to unsaved related object 'contest_of_ABC'.
Advertisement
Answer
You’re going to want to call super.save() on your MatchDetail before you created your ContestDetail object, not after, as you have it. Until super is called, your self object has no primary key (assuming it’s a new object being saved)
def save(self, *args, **kwargs): self.match_tick = self.match_date.timestamp() super(MatchDetail, self).save(*args, **kwargs) contest_obj_1 = ContestDetail( contest_of_ABC=self, contest_name="₹1000 Winnnings", filled_status = False, ) contest_obj_1.save()