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()
链接地址: http://www.djcxy.com/p/54170.html
上一篇: 像Odoo中的django信号
下一篇: 将django模型实例保存到另一个模型中