0
votes

I want to save two objects, one of them is related through ForeignKey('self').

I want to check if save() method was called through django admin or as recursive method from the save() itself. Since I want to save two instances of the object and not infinite amount of them.

The model:

prev_work = models.ForeignKey('self', on_delete=models.CASCADE,
editable=False, null=True, blank=True)

Code for saving:

prev_work = Work(chapter=self.chapter, job=self.job, prev_work=self)
prev_work.save()

I'm expecting to save two objects but I don't know how to stop the program from calling save each time it comes to the end of the method. I done it through other means but still I would like to know how can I check if method was called from django admin. Thanks!

1
It is not very clear what you are trying to achieve. - Stargazer

1 Answers

0
votes

It is not very clear what you are trying to achieve, but it looks like you want to call .save() recursively a limit number of times. If that is the case, you could use a custom keyword argument to the method that works as a flag or counter.

class Work(models.Model):
    def save(self, *args, **kwargs):
        # the default could be the max number of additional calls you want for this method
        call_x_more_times = kwargs.pop('call_x_more_times', 1)

        super().save(*args, **kwargs)
        # ... do other things, if you need to ...

        if call_x_more_times > 0:
            # set argument for next call, decreased by 1
            kwargs['call_x_more_times'] = call_x_more_times - 1
            self.save(*args, **kwargs)

We cannot help much more since you don't give much information in the question. Does this ehlp you?