thirdparty/google_appengine/lib/django/tests/modeltests/get_or_create/models.py
changeset 2866 a04b1e4126c4
parent 2864 2e0b0af889be
child 2868 9f7f269383f7
equal deleted inserted replaced
2864:2e0b0af889be 2866:a04b1e4126c4
     1 """
       
     2 33. get_or_create()
       
     3 
       
     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.
       
     6 """
       
     7 
       
     8 from django.db import models
       
     9 
       
    10 class Person(models.Model):
       
    11     first_name = models.CharField(maxlength=100)
       
    12     last_name = models.CharField(maxlength=100)
       
    13     birthday = models.DateField()
       
    14 
       
    15     def __str__(self):
       
    16         return '%s %s' % (self.first_name, self.last_name)
       
    17 
       
    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))
       
    22 >>> p.save()
       
    23 
       
    24 # Only one Person is in the database at this point.
       
    25 >>> Person.objects.count()
       
    26 1
       
    27 
       
    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)})
       
    30 
       
    31 # get_or_create() didn't have to create an object.
       
    32 >>> created
       
    33 False
       
    34 
       
    35 # There's still only one Person in the database.
       
    36 >>> Person.objects.count()
       
    37 1
       
    38 
       
    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)})
       
    41 >>> created
       
    42 True
       
    43 >>> Person.objects.count()
       
    44 2
       
    45 
       
    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)})
       
    48 >>> created
       
    49 False
       
    50 >>> Person.objects.count()
       
    51 2
       
    52 """}