views:

43

answers:

1

Here's the situation:

Let's say I have a model A in django. When I'm saving an object (of class A) I need to save it's fields into all other objects of this class. I mean I need every other A object to be copy of lat saved one.

When I use signals (post-save for example) I get a recursion (objects try to save each other I guess) and my python dies.

I men I expected that using .save() method on the same class in pre/post-save signal would cause a recursion but just don't know how to avoid it.

What do we do?

+2  A: 

This will work:

class YourModel(models.Model):
    name = models.CharField(max_length=50)

    def save_dupe(self):
        super(YourModel, self).save()

    def save(self, *args, **kwargs):
        super(YourModel, self).save(*args, **kwargs)
        for model in YourModel.objects.exclude(pk=self.pk):
            model.name = self.name
            # Repeat the above for all your other fields
            model.save_dupe()

If you have a lot of fields, you'll probably want to iterate over them when copying them to the other model. I'll leave that to you.

Aram Dulyan