简体   繁体   中英

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.
The "class" part comes from the markup they used when they wrote it.

So, what they actually meant in the Django documentation is:

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().




Original question

I found the following while reading the 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().


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.
Is the first one different from it? To me, it seems like it rather redefines the Model class.

class Model(**kwargs) is not a valid Python syntax , the latter would look like

class Model(SomeBaseClass):
    pass

Judging by the formatting (the line looks like a subheading), this must be a mistake in the Django documentation.

If you look at the Sphinx source of the page , you'll see that the "class" thing is actually a part of Sphinx markup. What they meant is

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.

The first line defines a class. The second line defines an instance of a class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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