[Django]-Copy a abstract model to another instance?

4๐Ÿ‘

โœ…

now i want to save one row from A to B, is there a easy way to do it? or do i need to copy every field on its own?

You can use the model_to_dict from django.forms to generate an initial kwargs dict:

from django.forms import model_to_dict
a = A.objects.get(..)
kwargs = model_to_dict(a)
kwargs.pop('id')
b = B.objects.create(**kwargs)
๐Ÿ‘คtuxcanfly

0๐Ÿ‘

You should have to copy each field in new instance of B and then save it.

But there is a shortcut way.

b_obj.__dict__ = a_obj.__dict__
#remove any foreign key/id/default fields
b_obj.__dict__.pop('id')
...
b_obj.save()

But its undocumented method, so has its own risks!

๐Ÿ‘คRohan

Leave a comment