简体   繁体   中英

Saving django model instance into another model

I have 2 models that inherit from an abstract model. I am using one for relevant data and the other one for archived data. They have the same fields and methods. I would like to create a post_save signal on model A so an instance will be created in model B whenever a new record is created, so far the options out there are not very elegant:

a = A.objects.get(id=1)
b = B()
model_dict = a.__dict__
model_dict.pop('id')
b.__dict__ = model_dict
b.save()

is there a better way to achieve this?

Note: These models contain foreign keys, as such, the model_to_dict function under django.forms does not work since it only provides the id of the related object.

I think that iterating over field list is more predictable way:

a = A.objects.get(id=1)
data = dict([field.name, getattr(a, field.name) for field in a._meta.fields])
b = B(**data)
b.pk = None
b.save()

Note: this doesn't handle ManyToMany relationships. M2M fields should be copied manually.

There's no need for any of that. Simply setting the id to None will cause it to save as a new instance.

a = A.objects.get(id=1)
a.id = None
a.save()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM