Ticket #10227: patch.diff

File patch.diff, 2.9 KB (added by rvdrijst, 6 years ago)

Patch with fix and tests

  • django/db/models/fields/related.py

     
    185185            return getattr(instance, self.cache_name)
    186186        except AttributeError:
    187187            params = {'%s__pk' % self.related.field.name: instance._get_pk_val()}
    188             rel_obj = self.related.model._default_manager.get(**params)
     188            try:
     189                rel_obj = self.related.model._default_manager.get(**params)
     190            except self.related.model.DoesNotExist:
     191                if self.related.field.null:
     192                    rel_obj = None
     193                else:
     194                    raise
    189195            setattr(instance, self.cache_name, rel_obj)
    190196            return rel_obj
    191197
  • tests/modeltests/one_to_one_null/__init__.py

     
     1
  • tests/modeltests/one_to_one_null/models.py

    Property changes on: tests/modeltests/one_to_one_null/__init__.py
    ___________________________________________________________________
    Added: svn:keywords
       + Id
    Added: svn:eol-style
       + native
    
     
     1"""
     214. One-to-one relationships that can be null.
     3
     4To define a one-to-one relationship, use ``OneToOneField()`` with null=True.
     5
     6In this example, a ``Shop`` can optionally have a ``Place``.
     7E.g. webshops need not have a place, so it can be None/null.
     8"""
     9
     10from django.db import models
     11
     12class 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
     19class 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
     33None
     34
     35>>> s1 = Shop(name='Shop', website='shop.com')
     36>>> s1.save()
     37>>> print s1.place
     38None
     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"""}
Back to Top