Add Django-1.2.1
[frozenviper.git] / Django-1.2.1 / tests / modeltests / get_or_create / models.py
blob56baa5c1ed1bdf3a6fc225dd05688d5b07d51232
1 """
2 33. get_or_create()
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 """
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))
27 >>> p.save()
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.
37 >>> created
38 False
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)})
46 >>> created
47 True
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)})
53 >>> created
54 False
55 >>> Person.objects.count()
58 # If you don't specify a value or default value for all required fields, you
59 # will get an error.
60 >>> try:
61 ... p, created = Person.objects.get_or_create(first_name='Tom', last_name='Smith')
62 ... except Exception, e:
63 ... if isinstance(e, IntegrityError):
64 ... print "Pass"
65 ... else:
66 ... print "Fail with %s" % type(e)
67 Pass
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')
72 >>> m.save()
73 >>> try:
74 ... m, created = ManualPrimaryKeyTest.objects.get_or_create(id=1, data='Different')
75 ... except Exception, e:
76 ... if isinstance(e, IntegrityError):
77 ... print "Pass"
78 ... else:
79 ... print "Fail with %s" % type(e)
80 Pass
81 >>> ManualPrimaryKeyTest.objects.get(id=1).data == 'Original'
82 True
83 """}