【问题标题】:What's the best way to create a model object in Django?在 Django 中创建模型对象的最佳方法是什么?
【发布时间】:2015-10-15 22:13:10
【问题描述】:
Author.objects.create(name="Joe")

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

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


类似问题:
- difference between objects.create() and object.save() in django orm
- Django: Difference between save() and create() from transaction perspective

【问题讨论】:

标签: 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(),将执行UPDATEINSERT,具体取决于对象的主键属性值。

【讨论】:

    【解决方案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() 将插入或更新。

      【讨论】:

        猜你喜欢
        • 2010-12-02
        • 2010-12-17
        • 1970-01-01
        • 1970-01-01
        • 2011-09-18
        • 1970-01-01
        • 2020-05-28
        • 1970-01-01
        • 2021-10-01
        相关资源
        最近更新 更多