Bri*_*ian 7 django django-models django-views
Author.objects.create(name="Joe")
Run Code Online (Sandbox Code Playgroud)
要么
an_author = Author(name="Joe")
an_author.save()
Run Code Online (Sandbox Code Playgroud)
这两者有什么区别?哪一个更好?
类似的问题:
- django orm中的objects.create()和object.save()之间的区别
- Django:从事务角度看save()和create()之间的区别
create()就像一个包装save()方法.
创建(**kwargs)
创建对象并将其全部保存在一个步骤中的便捷方法
Django的1.8 源代码的create()功能:
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
Run Code Online (Sandbox Code Playgroud)
为create(),一个force_insert参数而调用传递save()内部迫使save()到方法执行SQLINSERT和不执行UPDATE.它会强制在数据库中插入一个新行.
为save(),无论是一个UPDATE或INSERT将执行根据对象的主键属性值.
第一个是你使用的Manager方法create。它已经为您实现,并且会自动保存。
第二种方法是创建类的实例,Author然后调用保存。
所以总而言之,
Author.objects.create(name="Joe")创建-->保存()
另一个第一行执行创建,第二行执行保存。
在某些情况下,您需要始终调用管理器方法。例如,您需要对密码进行哈希处理。
# In here you are saving the un hashed password.
user = User(username="John")
user.password = "112233"
user.save()
# In here you are using the manager method,
# which provide for you hashing before saving the password.
user = User.objects.create_user(username="John", password="112233")
Run Code Online (Sandbox Code Playgroud)
所以基本上,在你的模型中将其视为设置者。如果您想在创建时始终修改数据,请使用管理器。
| 归档时间: |
|
| 查看次数: |
11598 次 |
| 最近记录: |