49
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.
- [Django]-Get user profile in django
- [Django]-Cannot access django app through ip address while accessing it through localhost
- [Django]-How to pass information using an HTTP redirect (in Django)
4
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.
- [Django]-How to run celery as a daemon in production?
- [Django]-Where can I find the error logs of nginx, using FastCGI and Django?
- [Django]-How can I see the raw SQL queries Django is running?
1
Basically, these two methods are equivalent. The usage of Model.objects.create
could be preferred since it is more suited to the style of Django.
- [Django]-Split models.py into several files
- [Django]-How to query Case-insensitive data in Django ORM?
- [Django]-Django: Example of generic relations using the contenttypes framework?
Source:stackexchange.com