如何克隆 Django 模型实例对象并将其保存到数据库中?

2022-01-31 00:00:00 python django django-models

问题描述

Foo.objects.get(pk="foo")
<Foo: test>

在数据库中,我想添加另一个对象,它是上面对象的副本.

In the database, I want to add another object which is a copy of the object above.

假设我的桌子只有一行.我想将第一行对象插入具有不同主键的另一行.我该怎么做?

Suppose my table has one row. I want to insert the first row object into another row with a different primary key. How can I do that?


解决方案

只需更改对象的主键并运行 save().

Just change the primary key of your object and run save().

obj = Foo.objects.get(pk=<some_existing_pk>)
obj.pk = None
obj.save()

如果您想要自动生成的密钥,请将新密钥设置为无.

If you want auto-generated key, set the new key to None.

更多关于更新/插入 这里.

More on UPDATE/INSERT here.

关于复制模型实例的官方文档:https://docs.djangoproject.com/en/2.2/topics/db/queries/#copying-model-instances

Official docs on copying model instances: https://docs.djangoproject.com/en/2.2/topics/db/queries/#copying-model-instances

相关文章