Sane OneToOne getter

1
2
3
4
5
6
7
8
from django.core.exceptions import ObjectDoesNotExist

def get_onetoone_or_none(obj, attr):
    """ Instead of letting django throw and exception, return None when a OneToOneField is null """
    try:
        return getattr(obj, attr)
    except ObjectDoesNotExist:
        return None

More like this

  1. View decorator to convert DoesNotExist (ObjectDoesNotExist) exceptions into Http404 exceptions by jammycakes 3 years, 8 months ago
  2. Improved Pickled Object Field by taavi223 3 years, 9 months ago
  3. Inline OneToOne relations in django-admin by bjourne 3 years ago
  4. Exists Filter OneToOneField in Admin by davidvaz 1 year, 6 months ago
  5. RelatedNullFilterSpec: django-admin custom filter all/null/not null/choices by Codeko 2 years, 7 months ago

Comments

gsakkis (on November 10, 2010):

There is a 2 year old ticket for this [1]; if you'd like to see it fixed properly some time in this century, you can try bumping it at the recent discussion on django-dev [2].

[1] http://code.djangoproject.com/ticket/10227

[2] http://bit.ly/auupjQ

#

(Forgotten your password?)