eugene
eugene

Reputation: 41725

Django update an instance using another instance

For instance, I have instance a1 and a2.

I'd like to update a1 to be same as a2. (except id field)

Following is what I came up with, not sure if it will work though and if there's a better way.

a2_data = model_to_dict(a2, exclude=['id'])

A.objcects.filter(id=a1.id).update(**a2_data)

Upvotes: 0

Views: 102

Answers (3)

pbaranay
pbaranay

Reputation: 585

The solution you suggested works:

from django.forms.models import model_to_dict
a2_data = model_to_dict(a2, exclude=['id'])
A.objects.filter(id=a1.id).update(**a2_data)

If you want to avoid the update statement, you could instead do something like:

for key, value in a2_data.items():
    setattr(a1, key, value)
a1.save()

However, this method won't work if any of your fields are ForeignKeys, whereas the first method does handle them properly.

Upvotes: 1

Ihor Pomaranskyy
Ihor Pomaranskyy

Reputation: 5621

I'm not sure if it will 100% work, but I believe it's worth trying:

a2 = A.objects.get(pk=a2_pk)
a1 = A.objects.get(pk=a1_pk)
a2.pk = a1.pk
a2.save()  # maybe force_update=True should be set here too

Upvotes: 0

Ihor Pomaranskyy
Ihor Pomaranskyy

Reputation: 5621

There is no thing like 'instance a1 the same as a2'. They can't be the same, at least they must have different IDs.

So it's impossible to do such updates in query. You have to filter the records which should be updated, to iterate over them and to do the changes you need.

Upvotes: 0

Related Questions