Commit 48562965 authored by Jacob Kaplan-Moss's avatar Jacob Kaplan-Moss
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
parent 2adbe116
Loading
Loading
Loading
Loading
+5 −2
Original line number Diff line number Diff line
@@ -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)
+9 −0
Original line number Diff line number Diff line
@@ -205,6 +205,15 @@ class QuerySet(object):
        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):
        """
        Looks up an object with the given kwargs, creating one if necessary.
+18 −0
Original line number Diff line number Diff line
@@ -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)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~

+5 −0
Original line number Diff line number Diff line
@@ -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>
"""