Added Manager.get_or_create()
git-svn-id: http://code.djangoproject.com/svn/django/trunk@3092 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
7e88ec5271
commit
b3a6348bc2
|
@ -65,6 +65,9 @@ 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 filter(self, *args, **kwargs):
|
||||
return self.get_query_set().filter(*args, **kwargs)
|
||||
|
||||
|
|
|
@ -205,6 +205,23 @@ 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 get_or_create(self, **kwargs):
|
||||
"""
|
||||
Looks up an object with the given kwargs, creating one if necessary.
|
||||
Returns a tuple of (object, created), where created is a boolean
|
||||
specifying whether an object was created.
|
||||
"""
|
||||
assert len(kwargs), 'get_or_create() must be passed at least one keyword argument'
|
||||
defaults = kwargs.pop('defaults', {})
|
||||
try:
|
||||
return self.get(**kwargs), False
|
||||
except self.model.DoesNotExist:
|
||||
params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
|
||||
params.update(defaults)
|
||||
obj = self.model(**params)
|
||||
obj.save()
|
||||
return obj, True
|
||||
|
||||
def latest(self, field_name=None):
|
||||
"""
|
||||
Returns the latest object, according to the model's 'get_latest_by'
|
||||
|
|
|
@ -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()``
|
||||
~~~~~~~~~~~
|
||||
|
||||
|
|
|
@ -0,0 +1,52 @@
|
|||
"""
|
||||
32. get_or_create()
|
||||
|
||||
get_or_create() does what it says: it tries to look up an object with the given
|
||||
parameters. If an object isn't found, it creates one with the given parameters.
|
||||
"""
|
||||
|
||||
from django.db import models
|
||||
|
||||
class Person(models.Model):
|
||||
first_name = models.CharField(maxlength=100)
|
||||
last_name = models.CharField(maxlength=100)
|
||||
birthday = models.DateField()
|
||||
|
||||
def __str__(self):
|
||||
return '%s %s' % (self.first_name, self.last_name)
|
||||
|
||||
API_TESTS = """
|
||||
# Acting as a divine being, create an Person.
|
||||
>>> from datetime import date
|
||||
>>> p = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
|
||||
>>> p.save()
|
||||
|
||||
# Only one Person is in the database at this point.
|
||||
>>> Person.objects.count()
|
||||
1
|
||||
|
||||
# get_or_create() a person with similar first names.
|
||||
>>> p, created = Person.objects.get_or_create(first_name='John', last_name='Lennon', defaults={'birthday': date(1940, 10, 9)})
|
||||
|
||||
# get_or_create() didn't have to create an object.
|
||||
>>> created
|
||||
False
|
||||
|
||||
# There's still only one Person in the database.
|
||||
>>> Person.objects.count()
|
||||
1
|
||||
|
||||
# get_or_create() a Person with a different name.
|
||||
>>> p, created = Person.objects.get_or_create(first_name='George', last_name='Harrison', defaults={'birthday': date(1943, 2, 25)})
|
||||
>>> created
|
||||
True
|
||||
>>> Person.objects.count()
|
||||
2
|
||||
|
||||
# If we execute the exact same statement, it won't create a Person.
|
||||
>>> p, created = Person.objects.get_or_create(first_name='George', last_name='Harrison', defaults={'birthday': date(1943, 2, 25)})
|
||||
>>> created
|
||||
False
|
||||
>>> Person.objects.count()
|
||||
2
|
||||
"""
|
Loading…
Reference in New Issue