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
这篇关于如何克隆 Django 模型实例对象并将其保存到数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!