【问题标题】:What's the best way to create a model object in Django?在 Django 中创建模型对象的最佳方法是什么?
【发布时间】:2015-10-15 22:13:10
【问题描述】:
【问题讨论】:
标签:
django
django-models
django-views
【解决方案1】:
create() 就像是 save() 方法的包装器。
创建(**kwargs)
一种创建对象并将其全部保存在一个中的便捷方法
步骤
Django 1.8 source code for 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
对于create(),在内部调用save() 时传递force_insert 参数,这会强制save() 方法执行SQL INSERT 和不执行UPDATE。它将在数据库中强制插入一个新行。
对于save(),将执行UPDATE 或INSERT,具体取决于对象的主键属性值。
【解决方案2】:
第一个你正在使用Manager方法create。它已经为您实施,它将自动保存。
第二种方法是创建Author 类的实例,然后调用保存。
总之,
Author.objects.create(name="Joe")create --> save()
另一个第一行创建,第二行保存。
在某些情况下,您需要始终调用管理器方法。例如,您需要对密码进行哈希处理。
# 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")
所以基本上,在您的模型中,将其视为二传手。如果您想在创建时始终修改数据,请使用管理器。
【解决方案3】:
Create 只是使用 kwargs 创建新对象的便捷代理。正如你在下面看到的,它会为你调用save():
来自Django Source:
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)
return obj
需要注意的一点是要保存的 force_insert 参数。这意味着 Django 将始终在此处使用 INSERT sql 语句而不是 UPDATE。默认值为 false,因此在您的第二个示例中 save() 将插入或更新。