Reputation: 6756
I have a model which can be described as:
Element: - element has one to one field with ElementData
ElementData: - it has ForeignKey to ElementImage - which describes default image
ElementImage: - it has ForeignKey to ElementData
ElementVideo: - it has foreignKey to ElementData
Now I want element and all subtables cloned. I tried to use snippet which I found here. I put this function to Element and ElementData and when I in element try to clone ElementData I have constraint violation. Can someone help me?
Upvotes: 1
Views: 1293
Reputation: 6756
my solution:
def clone(self):
old = self
images = old.element_data.images.all()
videos = old.element_data.videos.all()
element_data = self.element_data
element_data.id = None
element_data.save()
for image in images:
image.id = None
image.element_data = element_data
image.save()
for video in videos:
video.id = None
video.element_data = element_data
video.save()
new_kwargs = dict([(fld.name, getattr(old, fld.name)) for fld in old._meta.fields if fld.name != 'id']);
new_kwargs['element_data'] = element_data
return self.__class__.objects.create(**new_kwargs)
Please write what you think about it
Upvotes: 1
Reputation: 14487
Because Element has OneToOne relation to ElementData, you need to clone the ElementData before cloning Element. Like this:
class Element(...):
def clone(self):
new_kwargs = dict([(fld.name, getattr(old, fld.name)) for fld in old._meta.fields if fld.name != 'id']);
new_data = self.data.clone()
new_kwargs['data'] = new_data
return self.__class__.objects.create(**new_kwargs)
Upvotes: 3