Skip to main content
 首页 » 编程设计

python之Django之创建模型的新实例

2025年05月04日34java哥

回答

正如 Sergey 所指出的,class Model(**kwargs) 是无效的,是 Django 文档中的错字。
“类”部分来自他们编写时使用的标记。

因此,它们在 Django 文档中的实际含义是:

Creating objects

To create a new instance of a model, just instantiate it like any other Python class:

Model(**kwargs)

The keyword arguments are simply the names of the fields you’ve defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save().




原始问题

我在阅读 Django Docs about Model instances 时发现了以下内容:

Creating objects

To create a new instance of a model, just instantiate it like any other Python class:

class Model(**kwargs)

The keyword arguments are simply the names of the fields you’ve defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save().


这两个代码有什么区别?

class Model(**kwargs) 
new_model = Model(**kwargs) 


我知道第二个使用 kwargs 创建类模型的新实例。
跟第一个有区别吗?在我看来,它似乎重新定义了 Model 类。

请您参考如下方法:

class Model(**kwargs) 不是 valid Python syntax , 后者看起来像

class Model(SomeBaseClass): 
    pass 

从格式判断(该行看起来像副标题),这一定是 Django 文档中的一个错误。

如果您查看 Sphinx source of the page ,您会看到“类”实际上是 Sphinx 标记的一部分。他们的意思是

To create a new instance of a model, just instantiate it like any other Python class:

Model(**kwargs) 

The keyword arguments are simply the names of the fields you've defined on your model.