简体   繁体   English

Django-创建模型的新实例

[英]Django - create a new instance of a model

Answer 回答

As Sergey pointed out, class Model(**kwargs) is invalid, and is a typo in Django documentation. 正如Sergey所指出的那样, 类Model(** kwargs)是无效的,并且是Django文档中的错字。
The "class" part comes from the markup they used when they wrote it. “类”部分来自他们在编写时使用的标记。

So, what they actually meant in the Django documentation is: 因此,它们在Django文档中的实际含义是:

Creating objects 创建对象

To create a new instance of a model, just instantiate it like any other Python class: 要创建模型的新实例,只需像其他任何Python类一样实例化它:

Model(**kwargs) 型号(** 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(). 为此,您需要save()。




Original question 原始问题

I found the following while reading the Django Docs about Model instances : 在阅读有关Model实例Django文档时,我发现了以下内容

Creating objects 创建对象

To create a new instance of a model, just instantiate it like any other Python class: 要创建模型的新实例,只需像其他任何Python类一样实例化它:

class Model(**kwargs) 类模型(** 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(). 为此,您需要save()。


What is the difference between these two codes? 这两个代码有什么区别?

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


I know the second one creates a new instance of the class Model, with kwargs. 我知道第二个实例使用kwargs创建了Model类的新实例。
Is the first one different from it? 第一个与此不同吗? To me, it seems like it rather redefines the Model class. 在我看来,它似乎重新定义了Model类。

class Model(**kwargs) is not a valid Python syntax , the latter would look like class Model(**kwargs)不是有效的Python语法 ,后者看起来像

class Model(SomeBaseClass):
    pass

Judging by the formatting (the line looks like a subheading), this must be a mistake in the Django documentation. 从格式判断(该行看起来像一个子标题),这在Django文档中一定是错误的。

If you look at the Sphinx source of the page , you'll see that the "class" thing is actually a part of Sphinx markup. 如果查看页面Sphinx源 ,您会发现“类”实际上是Sphinx标记的一部分。 What they meant is 他们的意思是

To create a new instance of a model, just instantiate it like any other Python class: 要创建模型的新实例,只需像其他任何Python类一样实例化它:

 Model(**kwargs) 

The keyword arguments are simply the names of the fields you've defined on your model. 关键字参数只是您在模型上定义的字段的名称。

The first line defines a class. 第一行定义一个类。 The second line defines an instance of a class. 第二行定义了一个类的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM