I have a simple class that includes a GenericRelation
class Item(models.Model):
name = models.CharField ( max_length=50, null=True, blank=True )
image = generic.GenericRelation(Image)
class Image(models.Model):
file = models.FileField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
To make a copy of an Item I can set Item.id = None and save:
item = Item.objects.get(id=3)
item.id = None
item.save()
# item is now a copy of the original item
Unfortunately this doesn’t copy the image field to the new instance.
I tried manually copying it over:
item = Item.objects.get(id=3)
images = item.image.all()
item.id = None
item.save()
item.image = images
However this removes the images from the original instance, effectively moving them to the second instance instead of copying.
What’s a good way to copy the images over to the new instance?
To answer my own question: I ended up manually making a copy of the image and setting its object_id: