在Django中创建模型对象的最佳方式是什么? [英] What's the best way to create a model object in Django?

查看:172
本文介绍了在Django中创建模型对象的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  Author.objects.create(name =Joe)

  an_author =作者(name =Joe)
an_author.save()

这两者有什么区别?
哪一个更好?





类似问题:

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

- Django:从事务角度看save()和create()之间的区别

解决方案

create() save()方法。


创建(** kwargs) / strong>



创建对象并将其全部保存在一个
步骤中的便利方法


Django 1.8 函数:





使用给定的kwargs创建一个新对象,将其保存到数据库
并返回创建的对象。

obj = self.model(** kwargs)
self._for_write = True
obj.save(force_insert = True,using = self.db)#call这里的`save()`方法
return obj

对于 create() a force_insert 参数在调用 save()内部强制 save()方法执行SQL INSERT 并且不执行 UPDATE ,它将强制在数据库中插入一个新行。



code> save(),将执行更新 INSERT 取决于对象的主键属性值。


Author.objects.create(name="Joe")

or

an_author = Author(name="Joe") 
an_author.save() 

What's the difference between these two? Which one is better?


Similar questions:
-
difference between objects.create() and object.save() in django orm
- Django: Difference between save() and create() from transaction perspective

解决方案

create() is like a wrapper over save() method.

create(**kwargs)

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

Django 1.8 source code for create() function:

def create(self, **kwargs):
        """
        Creates a new object with the given kwargs, saving it to the database
        and returning the created object.
        """
        obj = self.model(**kwargs)
        self._for_write = True
        obj.save(force_insert=True, using=self.db) # calls the `save()` method here
        return obj

For create(), a force_insert parameter is passed while calling save() internally which forces the save() method to perform an SQL INSERT and not perform an UPDATE. It will forcibly insert a new row in the database.

For save(), either an UPDATE or INSERT will be performed depending on the object’s primary key attribute value.

这篇关于在Django中创建模型对象的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆