diff options
| author | Adrian Holovaty <adrian@holovaty.com> | 2006-06-07 00:09:29 +0000 |
|---|---|---|
| committer | Adrian Holovaty <adrian@holovaty.com> | 2006-06-07 00:09:29 +0000 |
| commit | b3a6348bc24de6dc7168e6c00f2d2d440b1fe748 (patch) | |
| tree | 573223e5b6077b6c7455dcae179025489894c298 /docs/db-api.txt | |
| parent | 7e88ec527107bd2c9023d48bcf177636eebc7e7a (diff) | |
Added Manager.get_or_create()
git-svn-id: http://code.djangoproject.com/svn/django/trunk@3092 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'docs/db-api.txt')
| -rw-r--r-- | docs/db-api.txt | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/docs/db-api.txt b/docs/db-api.txt index 3624620609..066521aa1d 100644 --- a/docs/db-api.txt +++ b/docs/db-api.txt @@ -705,6 +705,53 @@ The ``DoesNotExist`` exception inherits from except ObjectDoesNotExist: print "Either the entry or blog doesn't exist." +``get_or_create(**kwargs)`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A convenience method for looking up an object with the given kwargs, creating +one if necessary. + +Returns a tuple of ``(object, created)``, where ``object`` is the retrieved or +created object and ``created`` is a boolean specifying whether a new object was +created. + +This is meant as a shortcut to boilerplatish code. For example:: + + try: + obj = Person.objects.get(first_name='John', last_name='Lennon') + except Person.DoesNotExist: + obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9)) + obj.save() + +This pattern gets quite unwieldy as the number of fields in a model goes up. +The above example can be rewritten using ``get_or_create()`` like so:: + + obj, created = Person.objects.get_or_create(first_name='John', last_name='Lennon', + defaults={'birthday': date(1940, 10, 9)}) + +Any keyword arguments passed to ``get_or_create()`` -- *except* an optional one +called ``default`` -- will be used in a ``get()`` call. If an object is found, +``get_or_create()`` returns a tuple of that object and ``False``. If an object +is *not* found, ``get_or_create()`` will instantiate and save a new object, +returning a tuple of the new object and ``True``. The new object will be +created according to this algorithm:: + + defaults = kwargs.pop('defaults', {}) + params = dict([(k, v) for k, v in kwargs.items() if '__' not in k]) + params.update(defaults) + obj = self.model(**params) + obj.save() + +In English, that means start with any non-``'defaults'`` keyword argument that +doesn't contain a double underscore (which would indicate a non-exact lookup). +Then add the contents of ``defaults``, overriding any keys if necessary, and +use the result as the keyword arguments to the model class. + +Finally, if you have a field named ``defaults`` and want to use it as an exact +lookup in ``get_or_create()``, just use ``'defaults__exact'``, like so:: + + Foo.objects.get_or_create(defaults__exact='bar', defaults={'defaults': 'baz'}) + ``count()`` ~~~~~~~~~~~ |
