gpt4 book ai didi

python - django orm中objects.create()和object.save()的区别

转载 作者:IT老高 更新时间:2023-10-28 21:42:20 30 4
gpt4 key购买 nike

u = UserDetails.objects.create(first_name='jake',last_name='sullivan')
u.save()

UserDetails.objects.create()u.save() 都执行相同的 save() 功能。有什么区别?使用 create()save() 有什么额外的检查或好处吗?

类似问题:

最佳答案

The Django documentation says it is the same .把它放在一条线上只是更方便。您也可以在一行上创建一个 save(),但它会更冗长且可读性较差——很明显,您正在使用 create() 创建一个新对象> 方法。

create(**kwargs)

A convenience method for creating an object and saving it all in one step. Thus:

p = Person.objects.create(first_name="Bruce", last_name="Springsteen")

and:

p = Person(first_name="Bruce", last_name="Springsteen")
p.save(force_insert=True)

are equivalent.

The force_insert parameter is documented elsewhere, but all it means is that a new object will always be created. Normally you won’t need to worry about this. However, if your model contains a manual primary key value that you set and if that value already exists in the database, a call to create() will fail with an IntegrityError since primary keys must be unique. Be prepared to handle the exception if you are using manual primary keys.

关于python - django orm中objects.create()和object.save()的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23926385/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com