| 1 | """ |
| 2 | XX. create() |
| 3 | |
| 4 | ``create()`` does what it says: it tries to create a new object with the |
| 5 | given parameters. |
| 6 | """ |
| 7 | |
| 8 | from django.db import models, transaction, IntegrityError |
| 9 | |
| 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() |
| 14 | |
| 15 | def __unicode__(self): |
| 16 | return u'%s %s' % (self.first_name, self.last_name) |
| 17 | |
| 18 | class ManualPrimaryKeyTest(models.Model): |
| 19 | id = models.IntegerField(primary_key=True) |
| 20 | data = models.CharField(max_length=100) |
| 21 | |
| 22 | __test__ = {'API_TESTS':""" |
| 23 | # Acting as a divine being, create an Person. |
| 24 | >>> from datetime import date |
| 25 | >>> p = Person.objects.create(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9)) |
| 26 | |
| 27 | # Only one Person is in the database at this point. |
| 28 | >>> Person.objects.count() |
| 29 | 1 |
| 30 | |
| 31 | # If you don't specify a value or default value for all required fields, you |
| 32 | # will get an error. |
| 33 | >>> try: |
| 34 | ... sid = transaction.savepoint() |
| 35 | ... Person.objects.create(first_name='Tom', last_name='Smith') |
| 36 | ... transaction.savepoint.commit(sid) |
| 37 | ... except Exception, e: |
| 38 | ... if isinstance(e, IntegrityError): |
| 39 | ... transaction.savepoint_rollback(sid) |
| 40 | ... print "Pass" |
| 41 | ... else: |
| 42 | ... print "Fail with %s" % type(e) |
| 43 | Pass |
| 44 | |
| 45 | # If you specify an existing primary key, but different other fields, then you |
| 46 | # will get an error and data will not be updated. |
| 47 | >>> m = ManualPrimaryKeyTest(id=1, data='Original') |
| 48 | >>> m.save() |
| 49 | >>> try: |
| 50 | ... sid = transaction.savepoint() |
| 51 | ... ManualPrimaryKeyTest.objects.create(id=1, data='Different') |
| 52 | ... transaction.savepoint_commit(sid) |
| 53 | ... except Exception, e: |
| 54 | ... if isinstance(e, IntegrityError): |
| 55 | ... transaction.savepoint_rollback(sid) |
| 56 | ... print "Pass" |
| 57 | ... else: |
| 58 | ... print "Fail with %s" % type(e) |
| 59 | Pass |
| 60 | >>> ManualPrimaryKeyTest.objects.get(id=1).data == 'Original' |
| 61 | True |
| 62 | """} |