1👍
Here’s my shot at it. If you need it to duplicate every time you make any changes, then override the model save
method. Note that this will not have any effect when executing .update()
on a queryset.
class Invoice(models.Model):
number = models.CharField(max_length=15)
def save(self, *args, **kwargs):
if not self.pk:
# if we dont have a pk set yet, it is the first time we are saving. Nothing to duplicate.
super(Invoice, self).save(*args, **kwargs)
else:
# save the line items before we duplicate
lines = list(self.line_set.all())
self.pk = None
super(Invoice, self).save(*args, **kwargs)
for line in lines:
line.pk = None
line.invoice = self
line.save()
This will create a duplicate Invoice
every time you call .save()
on an existing record. It will also create duplicates for every Line
tied to that Invoice
. You may need to do something similar every time you update a Line
as well.
This of course is not very generic. This is specific to these 2 models. If you need something more generic, you could loop over every field, determine what kind of field it is, make needed duplicates, etc.
Source:stackexchange.com