Rah*_*pta 9

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(),无论是一个UPDATEINSERT将执行根据对象的主键属性值.


Oth*_*man 5

第一个是你使用的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)

所以基本上,在你的模型中将其视为设置者。如果您想在创建时始终修改数据,请使用管理器。