views:

75

answers:

1

Hello everybody,

ok i think this is very basic, but since i'm new to django i don't know how to handle this.. I need to copy an instance of a django-model. As explained here, there is a problem with copying many2many relations. But the attachment "django-model-copying.diff" has that function i guess. So i don't know - does my django already have that function? I don't know how to call it.. Help would be appreciated :)

thanks in advance!

A: 

You can just do the following:

m = MyModel.objects.get(pk=1)
m.id = None
m.save()

That way new instance will be created with new id of course in case of any unique properties it will trigger errors during validation.

NOTE: As for the function you've mentioned - it is not yet added to the trunk, the status is design decision needed, but if you know what you're doing you can manually apply the diff to your django instance - it's called patching btw. Here are some details about how to do it: http://ariejan.net/2007/07/03/how-to-create-and-apply-a-patch-with-subversion/.

bx2
yeah - i know that.. but this way it loses all m2m-relationships..
Peter
I guess you could add `__copy__()`/`__deepcopy__()` functions to your model and then save the m2m values. Or maybe using `pickle`.. I'll try to solve this one out - quite interesting ;)
bx2
Problem is that you have to copy 'through' table also, to point the new model on one end while pointing to the other end of the relation..
bx2
As Peter and bx2 already mentionned, this doesn't address the main problem which is m2m relationships.
bruno desthuilliers
The main problem is "So i don't know - does my django already have that function?" and I wrote about it in my answer so WTF? Read first, then add minus scores!
bx2