| | 1 | """ |
| | 2 | 14. One-to-one relationships that can be null. |
| | 3 | |
| | 4 | To define a one-to-one relationship, use ``OneToOneField()`` with null=True. |
| | 5 | |
| | 6 | In this example, a ``Shop`` can optionally have a ``Place``. |
| | 7 | E.g. webshops need not have a place, so it can be None/null. |
| | 8 | """ |
| | 9 | |
| | 10 | from django.db import models |
| | 11 | |
| | 12 | class Place(models.Model): |
| | 13 | name = models.CharField(max_length=50) |
| | 14 | address = models.CharField(max_length=80) |
| | 15 | |
| | 16 | def __unicode__(self): |
| | 17 | return u"%s the place" % self.name |
| | 18 | |
| | 19 | class Shop(models.Model): |
| | 20 | place = models.OneToOneField(Place, null=True) |
| | 21 | name = models.CharField(max_length=50) |
| | 22 | website = models.URLField() |
| | 23 | |
| | 24 | def __unicode__(self): |
| | 25 | return u"%s the shop" % self.name |
| | 26 | |
| | 27 | __test__ = {'API_TESTS':""" |
| | 28 | # Create a place |
| | 29 | >>> p1 = Place(name='Shop.com retail point', address='101 Somestr') |
| | 30 | >>> p1.save() |
| | 31 | |
| | 32 | >>> print p1.shop |
| | 33 | None |
| | 34 | |
| | 35 | >>> s1 = Shop(name='Shop', website='shop.com') |
| | 36 | >>> s1.save() |
| | 37 | >>> print s1.place |
| | 38 | None |
| | 39 | |
| | 40 | >>> s1.place = p1 |
| | 41 | >>> s1.save() |
| | 42 | |
| | 43 | >>> s1.place |
| | 44 | <Place: Shop.com retail point the place> |
| | 45 | |
| | 46 | # update p1 to reflect the new relation |
| | 47 | >>> p1 = Place.objects.get(pk=p1.pk) |
| | 48 | >>> p1.shop |
| | 49 | <Shop: Shop the shop> |
| | 50 | |
| | 51 | |
| | 52 | """} |