4
get_or_create() does what it says: it tries to look up an object with the given
5
parameters. If an object isn't found, it creates one with the given parameters.
8
from django.db import models
10
class Person(models.Model):
11
first_name = models.CharField(max_length=100)
12
last_name = models.CharField(max_length=100)
13
birthday = models.DateField()
15
def __unicode__(self):
16
return u'%s %s' % (self.first_name, self.last_name)
18
__test__ = {'API_TESTS':"""
19
# Acting as a divine being, create an Person.
20
>>> from datetime import date
21
>>> p = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
24
# Only one Person is in the database at this point.
25
>>> Person.objects.count()
28
# get_or_create() a person with similar first names.
29
>>> p, created = Person.objects.get_or_create(first_name='John', last_name='Lennon', defaults={'birthday': date(1940, 10, 9)})
31
# get_or_create() didn't have to create an object.
35
# There's still only one Person in the database.
36
>>> Person.objects.count()
39
# get_or_create() a Person with a different name.
40
>>> p, created = Person.objects.get_or_create(first_name='George', last_name='Harrison', defaults={'birthday': date(1943, 2, 25)})
43
>>> Person.objects.count()
46
# If we execute the exact same statement, it won't create a Person.
47
>>> p, created = Person.objects.get_or_create(first_name='George', last_name='Harrison', defaults={'birthday': date(1943, 2, 25)})
50
>>> Person.objects.count()