1
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.
0
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.
- Getting error in mixins when I try to login as a user
- Assertion fails with same object
- Why am I getting an integrity error django?
- How do we tell where a django redirect comes from
0
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
Source:stackexchange.com