Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added {{{Manager.create()}}} method to create and save an object in a…

… single step.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@3217 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 48562965b900bd8d4ba5f6fef4b635af844b5cee 1 parent 2adbe11
@jacobian jacobian authored
View
7 django/db/models/manager.py
@@ -69,8 +69,11 @@ def extra(self, *args, **kwargs):
def get(self, *args, **kwargs):
return self.get_query_set().get(*args, **kwargs)
- def get_or_create(self, *args, **kwargs):
- return self.get_query_set().get_or_create(*args, **kwargs)
+ def get_or_create(self, **kwargs):
+ return self.get_query_set().get_or_create(**kwargs)
+
+ def create(self, **kwargs):
+ return self.get_query_set().create(**kwargs)
def filter(self, *args, **kwargs):
return self.get_query_set().filter(*args, **kwargs)
View
9 django/db/models/query.py
@@ -204,6 +204,15 @@ def get(self, *args, **kwargs):
raise self.model.DoesNotExist, "%s matching query does not exist." % self.model._meta.object_name
assert len(obj_list) == 1, "get() returned more than one %s -- it returned %s! Lookup parameters were %s" % (self.model._meta.object_name, len(obj_list), kwargs)
return obj_list[0]
+
+ def create(self, **kwargs):
+ """
+ Create a new object with the given kwargs, saving it to the database
+ and returning the created object.
+ """
+ obj = self.model(**kwargs)
+ obj.save()
+ return obj
def get_or_create(self, **kwargs):
"""
View
18 docs/db-api.txt
@@ -60,6 +60,10 @@ the database until you explicitly call ``save()``.
The ``save()`` method has no return value.
+To create an object and save it all in one step see the `create`__ method.
+
+__ `create(**kwargs)`_
+
Auto-incrementing primary keys
------------------------------
@@ -705,6 +709,20 @@ The ``DoesNotExist`` exception inherits from
except ObjectDoesNotExist:
print "Either the entry or blog doesn't exist."
+``create(**kwargs)``
+~~~~~~~~~~~~~~~~~~~~
+
+A convenience method for creating an object and saving it all in one step. Thus::
+
+ p = Person.objects.create(first_name="Bruce", last_name="Springsteen")
+
+and::
+
+ p = Person(first_name="Bruce", last_name="Springsteen")
+ p.save()
+
+are equivalent.
+
``get_or_create(**kwargs)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~
View
5 tests/modeltests/basic/models.py
@@ -347,4 +347,9 @@ def __str__(self):
>>> a101 = Article.objects.get(pk=101)
>>> a101.headline
'Article 101'
+
+# You can create saved objects in a single step
+>>> a10 = Article.objects.create(headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45))
+>>> Article.objects.get(headline="Article 10")
+<Article: Article 10>
"""
Please sign in to comment.
Something went wrong with that request. Please try again.