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
9 from django
.db
import models
, IntegrityError
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()
16 def __unicode__(self
):
17 return u
'%s %s' % (self
.first_name
, self
.last_name
)
19 class ManualPrimaryKeyTest(models
.Model
):
20 id = models
.IntegerField(primary_key
=True)
21 data
= models
.CharField(max_length
=100)
23 __test__
= {'API_TESTS':"""
24 # Acting as a divine being, create an Person.
25 >>> from datetime import date
26 >>> p = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
29 # Only one Person is in the database at this point.
30 >>> Person.objects.count()
33 # get_or_create() a person with similar first names.
34 >>> p, created = Person.objects.get_or_create(first_name='John', last_name='Lennon', defaults={'birthday': date(1940, 10, 9)})
36 # get_or_create() didn't have to create an object.
40 # There's still only one Person in the database.
41 >>> Person.objects.count()
44 # get_or_create() a Person with a different name.
45 >>> p, created = Person.objects.get_or_create(first_name='George', last_name='Harrison', defaults={'birthday': date(1943, 2, 25)})
48 >>> Person.objects.count()
51 # If we execute the exact same statement, it won't create a Person.
52 >>> p, created = Person.objects.get_or_create(first_name='George', last_name='Harrison', defaults={'birthday': date(1943, 2, 25)})
55 >>> Person.objects.count()
58 # If you don't specify a value or default value for all required fields, you
61 ... p, created = Person.objects.get_or_create(first_name='Tom', last_name='Smith')
62 ... except Exception, e:
63 ... if isinstance(e, IntegrityError):
66 ... print "Fail with %s" % type(e)
69 # If you specify an existing primary key, but different other fields, then you
70 # will get an error and data will not be updated.
71 >>> m = ManualPrimaryKeyTest(id=1, data='Original')
74 ... m, created = ManualPrimaryKeyTest.objects.get_or_create(id=1, data='Different')
75 ... except Exception, e:
76 ... if isinstance(e, IntegrityError):
79 ... print "Fail with %s" % type(e)
81 >>> ManualPrimaryKeyTest.objects.get(id=1).data == 'Original'