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


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)