Hulk
Hulk

Reputation: 34170

Copying contents of a model

If there exists an old data of a model say ,

query=Emp.objects.filter(pk=profile.id)

Is there a easier way to copy the same values into the same model again..

Now that the id will be different so..

I have this requirement.

Thanks..

Upvotes: 1

Views: 298

Answers (2)

Ludwik Trammer
Ludwik Trammer

Reputation: 25032

object = Emp.objects.get(pk=profile.id)
object.save(force_insert=True)

It's much more explicit then removing primary key's value. See also "forcing an insert or update" in Django documentation.

Upvotes: 7

KillianDS
KillianDS

Reputation: 17176

Unless you have a complex model with inheritance, this should work:

query.pk = None
query.save() #Will insert new record

For the other case I found a snippet here, did not test it however.

Upvotes: 3

Related Questions