| | 708 | ``get_or_create(**kwargs)`` |
|---|
| | 709 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|---|
| | 710 | |
|---|
| | 711 | A convenience method for looking up an object with the given kwargs, creating |
|---|
| | 712 | one if necessary. |
|---|
| | 713 | |
|---|
| | 714 | Returns a tuple of ``(object, created)``, where ``object`` is the retrieved or |
|---|
| | 715 | created object and ``created`` is a boolean specifying whether a new object was |
|---|
| | 716 | created. |
|---|
| | 717 | |
|---|
| | 718 | This is meant as a shortcut to boilerplatish code. For example:: |
|---|
| | 719 | |
|---|
| | 720 | try: |
|---|
| | 721 | obj = Person.objects.get(first_name='John', last_name='Lennon') |
|---|
| | 722 | except Person.DoesNotExist: |
|---|
| | 723 | obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9)) |
|---|
| | 724 | obj.save() |
|---|
| | 725 | |
|---|
| | 726 | This pattern gets quite unwieldy as the number of fields in a model goes up. |
|---|
| | 727 | The above example can be rewritten using ``get_or_create()`` like so:: |
|---|
| | 728 | |
|---|
| | 729 | obj, created = Person.objects.get_or_create(first_name='John', last_name='Lennon', |
|---|
| | 730 | defaults={'birthday': date(1940, 10, 9)}) |
|---|
| | 731 | |
|---|
| | 732 | Any keyword arguments passed to ``get_or_create()`` -- *except* an optional one |
|---|
| | 733 | called ``default`` -- will be used in a ``get()`` call. If an object is found, |
|---|
| | 734 | ``get_or_create()`` returns a tuple of that object and ``False``. If an object |
|---|
| | 735 | is *not* found, ``get_or_create()`` will instantiate and save a new object, |
|---|
| | 736 | returning a tuple of the new object and ``True``. The new object will be |
|---|
| | 737 | created according to this algorithm:: |
|---|
| | 738 | |
|---|
| | 739 | defaults = kwargs.pop('defaults', {}) |
|---|
| | 740 | params = dict([(k, v) for k, v in kwargs.items() if '__' not in k]) |
|---|
| | 741 | params.update(defaults) |
|---|
| | 742 | obj = self.model(**params) |
|---|
| | 743 | obj.save() |
|---|
| | 744 | |
|---|
| | 745 | In English, that means start with any non-``'defaults'`` keyword argument that |
|---|
| | 746 | doesn't contain a double underscore (which would indicate a non-exact lookup). |
|---|
| | 747 | Then add the contents of ``defaults``, overriding any keys if necessary, and |
|---|
| | 748 | use the result as the keyword arguments to the model class. |
|---|
| | 749 | |
|---|
| | 750 | Finally, if you have a field named ``defaults`` and want to use it as an exact |
|---|
| | 751 | lookup in ``get_or_create()``, just use ``'defaults__exact'``, like so:: |
|---|
| | 752 | |
|---|
| | 753 | Foo.objects.get_or_create(defaults__exact='bar', defaults={'defaults': 'baz'}) |
|---|
| | 754 | |
|---|