| 1 |
""" |
|---|
| 2 |
33. get_or_create() |
|---|
| 3 |
|
|---|
| 4 |
``get_or_create()`` does what it says: it tries to look up an object with the |
|---|
| 5 |
given parameters. If an object isn't found, it creates one with the given |
|---|
| 6 |
parameters. |
|---|
| 7 |
""" |
|---|
| 8 |
|
|---|
| 9 |
from django.db import models, IntegrityError |
|---|
| 10 |
|
|---|
| 11 |
class Person(models.Model): |
|---|
| 12 |
first_name = models.CharField(max_length=100) |
|---|
| 13 |
last_name = models.CharField(max_length=100) |
|---|
| 14 |
birthday = models.DateField() |
|---|
| 15 |
|
|---|
| 16 |
def __unicode__(self): |
|---|
| 17 |
return u'%s %s' % (self.first_name, self.last_name) |
|---|
| 18 |
|
|---|
| 19 |
__test__ = {'API_TESTS':""" |
|---|
| 20 |
# Acting as a divine being, create an Person. |
|---|
| 21 |
>>> from datetime import date |
|---|
| 22 |
>>> p = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9)) |
|---|
| 23 |
>>> p.save() |
|---|
| 24 |
|
|---|
| 25 |
# Only one Person is in the database at this point. |
|---|
| 26 |
>>> Person.objects.count() |
|---|
| 27 |
1 |
|---|
| 28 |
|
|---|
| 29 |
# get_or_create() a person with similar first names. |
|---|
| 30 |
>>> p, created = Person.objects.get_or_create(first_name='John', last_name='Lennon', defaults={'birthday': date(1940, 10, 9)}) |
|---|
| 31 |
|
|---|
| 32 |
# get_or_create() didn't have to create an object. |
|---|
| 33 |
>>> created |
|---|
| 34 |
False |
|---|
| 35 |
|
|---|
| 36 |
# There's still only one Person in the database. |
|---|
| 37 |
>>> Person.objects.count() |
|---|
| 38 |
1 |
|---|
| 39 |
|
|---|
| 40 |
# get_or_create() a Person with a different name. |
|---|
| 41 |
>>> p, created = Person.objects.get_or_create(first_name='George', last_name='Harrison', defaults={'birthday': date(1943, 2, 25)}) |
|---|
| 42 |
>>> created |
|---|
| 43 |
True |
|---|
| 44 |
>>> Person.objects.count() |
|---|
| 45 |
2 |
|---|
| 46 |
|
|---|
| 47 |
# If we execute the exact same statement, it won't create a Person. |
|---|
| 48 |
>>> p, created = Person.objects.get_or_create(first_name='George', last_name='Harrison', defaults={'birthday': date(1943, 2, 25)}) |
|---|
| 49 |
>>> created |
|---|
| 50 |
False |
|---|
| 51 |
>>> Person.objects.count() |
|---|
| 52 |
2 |
|---|
| 53 |
|
|---|
| 54 |
# If you don't specify a value or default value for all required fields, you |
|---|
| 55 |
# will get an error. |
|---|
| 56 |
>>> try: |
|---|
| 57 |
... p, created = Person.objects.get_or_create(first_name='Tom', last_name='Smith') |
|---|
| 58 |
... except Exception, e: |
|---|
| 59 |
... if isinstance(e, IntegrityError): |
|---|
| 60 |
... print "Pass" |
|---|
| 61 |
... else: |
|---|
| 62 |
... print "Fail with %s" % type(e) |
|---|
| 63 |
Pass |
|---|
| 64 |
"""} |
|---|