mirror of https://github.com/django/django.git
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
This commit is contained in:
parent
2adbe11678
commit
48562965b9
|
@ -69,8 +69,11 @@ class Manager(object):
|
|||
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)
|
||||
|
|
|
@ -204,6 +204,15 @@ class QuerySet(object):
|
|||
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):
|
||||
"""
|
||||
|
|
|
@ -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)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
|
|
@ -347,4 +347,9 @@ API_TESTS += """
|
|||
>>> 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>
|
||||
"""
|
||||
|
|
Loading…
Reference in New Issue