简体   繁体   English

将Django模型实例保存到另一个模型中

[英]Saving django model instance into another model

I have 2 models that inherit from an abstract model. 我有2个从抽象模型继承的模型。 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上创建一个post_save信号,以便每当创建新记录时都将在模型B中创建一个实例,到目前为止,那里的选项不是很好:

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. 注意:这些模型包含外键,因此django.forms下的model_to_dict函数不起作用,因为它仅提供相关对象的ID。

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. 注意:这不处理ManyToMany关系。 M2M fields should be copied manually. M2M字段应手动复制。

There's no need for any of that. 不需要任何。 Simply setting the id to None will cause it to save as a new instance. 只需将id设置为None即可将其另存为新实例。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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