views:

91

answers:

2

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..

+3  A: 

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.

KillianDS
Sorry but i wanted the duplicate records in the same table which will have a different id since id is PK
Hulk
`query` is here a `QuerySet` so `query.pk = None` won't work. Better use `.object.get` instead of `.objects.filter`
Clément
you're right, it should be get instead of filter (or you should loop over the filtered objects). And Hulk, sory but I really don't understand your question?
KillianDS
if there are entries like id=1,name="Tom" desg="Senior manager"How to copy the same values into the table when now all the data remains the same except for id
Hulk
well, do as I say, but you only have to make sure the 'query' variable of my code is a model instance (e.g. you got by calling .get() or iterating over a queryset). setting pk to None and calling the save method will make sure the object will be duplicated with a new id.
KillianDS
+7  A: 
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.

Ludwik Trammer