Ticket #1463: m2o-patch.diff

File m2o-patch.diff, 1.9 KB (added by Malcolm Tredinnick <malcolm@…>, 19 years ago)

Return None when ForeignKey-related object does not exist

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

     
    115115        except AttributeError:
    116116            val = getattr(instance, self.field.attname)
    117117            if val is None:
    118                 raise self.field.rel.to.DoesNotExist
     118                return val
    119119            other_field = self.field.rel.get_related_field()
    120120            if other_field.rel:
    121121                params = {'%s__pk' % self.field.rel.field_name: val}
  • tests/modeltests/m2o_recursive/models.py

     
    3131>>> r.child_set.get(name__startswith='Child')
    3232Child category
    3333>>> r.parent
    34 Traceback (most recent call last):
    35     ...
    36 DoesNotExist
    3734
    3835>>> c.child_set.all()
    3936[]
  • tests/modeltests/many_to_one_null/models.py

     
    6262>>> a3.id
    63633
    6464>>> a3.reporter
    65 Traceback (most recent call last):
    66     ...
    67 DoesNotExist
    6865
    6966>>> a3 = Article.objects.get(pk=3)
    7067>>> print a3.reporter.id
    7168Traceback (most recent call last):
    72     ...
    73 DoesNotExist
     69   ...
     70AttributeError: 'NoneType' object has no attribute 'id'
    7471
    75 # Accessing an article's 'reporter' attribute throws ReporterDoesNotExist
    76 # if the reporter is set to None.
     72# Accessing an article's 'reporter' attribute returns None if the reporter is
     73# set to None.
    7774>>> a3.reporter
    78 Traceback (most recent call last):
    79     ...
    80 DoesNotExist
    8175
    8276# To retrieve the articles with no reporters set, use "reporter__isnull=True".
    8377>>> Article.objects.filter(reporter__isnull=True)
Back to Top