Django-创建mod的新实例

2024-04-23 17:19:20 发布

您现在位置:Python中文网/ 问答频道 /正文

回答

正如Sergey指出的,类模型(**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。
第一个不同吗?在我看来,它似乎重新定义了模型类。


Tags: ofthedjango文档模型creatingyounew
2条回答

第一行定义了一个类。 第二行定义类的实例。

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.

相关问题 更多 >