Django

Code

root/django/trunk/tests/modeltests/get_or_create/models.py

Revision 8450, 1.9 kB (checked in by mtredinnick, 1 week ago)

There are some variations in the printed names of exceptions between Oracle and
other database backends, but the exception classes should still be the same.
This commit changes the way the tests check for specific database errors to be
more portable between implementations.

It's possible these tests will still fail if, e.g., Oracle doesn't raise
IntegrityError (but raises DatabaseError?) when we except it to, but we can
cross that bridge if and when it appears.

  • Property svn:eol-style set to native
Line 
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 """}
Note: See TracBrowser for help on using the browser.