Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Model() vs Model.objects.create()

What it the difference between running two commands:

foo = FooModel() 

and

bar = BarModel.objects.create() 

Does the second one immediately create a BarModel in the database, while for FooModel, the save() method has to be called explicitly to add it to the database?

like image 564
0leg Avatar asked Oct 31 '14 10:10

0leg


People also ask

What is model model in Django?

A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you're storing. Generally, each model maps to a single database table. The basics: Each model is a Python class that subclasses django.

Does objects create save?

Conclusion: Model. objects. create() internally do model initialization and perform save with force_insert=True .

How do I create an instance of a Django model?

To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are 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() .

Why do we create models in Django?

Django web applications access and manage data through Python objects referred to as models. Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc.


1 Answers

https://docs.djangoproject.com/en/stable/topics/db/queries/#creating-objects

To create and save an object in a single step, use the create() method.

like image 98
madzohan Avatar answered Sep 19 '22 13:09

madzohan