Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model manager objects.create where is the documentation?

Tags:

python

django

I always read that I should use

model = Model(a=5, b=6)
model.save()

But I just saw there is a manager function create, because I saw an opensource django app using it.

model = Model.objects.create(a=5, b=6)
print model.pk
1

So is it suggested to use it? Or is it still preferred to use the .save method. I'm guessing that objects.create will try to create it no matter what, whereas save may save an existing object if the pk is specified.

These are the docs that I found: https://docs.djangoproject.com/en/dev/topics/db/queries/#creating-objects

like image 778
Sam Stoelinga Avatar asked Mar 30 '12 09:03

Sam Stoelinga


People also ask

Where are Django models located?

Since Django only looks for models under the Python path <app>. models , you must declare a relative import in the main models.py file -- for each of the models inside sub-folders -- to make them visible to the app.

How do I create a new model object in Django?

Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

How object is stored in Django model?

A model in Django is supposed to correlate to a table in the database, so that each field in the model will actually be a field in the table for that model. To achieve what you're trying to do, you need to create a second model, which will be the object you want to store.


3 Answers

p = Person.objects.create(first_name="Bruce", last_name="Springsteen")

equivalent to:

p = Person(first_name="Bruce", last_name="Springsteen") 
p.save(force_insert=True)

The force_insert means that a new object will always be created.
Normally you won’t need to worry about this. However, if your model contains a manual primary key value that you set and if that value already exists in the database, a call to create() will fail with an IntegrityError since primary keys must be unique. Be prepared to handle the exception if you are using manual primary keys.

like image 75
suhailvs Avatar answered Oct 19 '22 17:10

suhailvs


It's in the page "QuerySet API reference", linked from the documentation index.

like image 37
Daniel Roseman Avatar answered Oct 19 '22 19:10

Daniel Roseman


create essentially does the same. below is the source code for create.

def create(self, **kwargs):
    """
    Creates a new object with the given kwargs, saving it to the database
    and returning the created object.
    """
    obj = self.model(**kwargs)
    self._for_write = True
    obj.save(force_insert=True, using=self.db)
    return obj

it creates an instance and then saves it.

like image 3
rajesh.kanakabandi Avatar answered Oct 19 '22 19:10

rajesh.kanakabandi