Opened 18 months ago

Closed 16 months ago

Last modified 16 months ago

#22048 closed Cleanup/optimization (fixed)

Document ways of checking for OneToOneField

Reported by: EvilDMP Owned by: code22
Component: Documentation Version: master
Severity: Normal Keywords: afraid-to-commit
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

https://docs.djangoproject.com/en/dev/topics/db/examples/one_to_one/#one-to-one-relationships points out that if you try to follow the related_name of a OneToOneField to something that doesn't exist, you'll get a DoesNotExist error.

What's missing is advice on how to check if there's a related object.

The most obvious is hasattr. Using the Restaurant/Place example in https://docs.djangoproject.com/en/dev/topics/db/examples/one_to_one/#one-to-one-relationships: hasattr(place, 'restaurant').

I've also seen https://djangosnippets.org/snippets/2254/ (uses ObjectDoesNotExist) and even things like http://stackoverflow.com/a/14743656/2422705 (uses select_related).

It should also be explained a little more why a missing object returns a DoesNotExist, rather than say None.

Change History (9)

comment:1 Changed 18 months ago by timo

  • Triage Stage changed from Unreviewed to Accepted
  • Type changed from Uncategorized to Cleanup/optimization

comment:2 Changed 17 months ago by code22

  • Owner changed from nobody to code22
  • Status changed from new to assigned

comment:3 Changed 17 months ago by code22

pull request for this ticket: https://github.com/django/django/pull/2356

comment:4 Changed 17 months ago by code22

i've made some improvements to my pull request

comment:5 Changed 17 months ago by code22

another improvement ready for checking

comment:6 Changed 17 months ago by timo

  • Has patch set

comment:7 Changed 16 months ago by Tim Graham <timograham@…>

  • Resolution set to fixed
  • Status changed from assigned to closed

In ec08d62a20f55cfdfb9fbd21d8bc5627c54337c7:

Fixed #22048 - Enhanced docs to cover nonexistent one-to-one relationships.

Thanks EvilDMP for the suggestion.

comment:8 Changed 16 months ago by Tim Graham <timograham@…>

In eb1600e9d1916d9db40ce1dce101224bd8859add:

[1.7.x] Fixed #22048 - Enhanced docs to cover nonexistent one-to-one relationships.

Thanks EvilDMP for the suggestion.

Backport of ec08d62a20 from master

comment:9 Changed 16 months ago by Tim Graham <timograham@…>

In 38096da5c0db7e7a3bb5b6e977f8e17adbf389ac:

[1.6.x] Fixed #22048 - Enhanced docs to cover nonexistent one-to-one relationships.

Thanks EvilDMP for the suggestion.

Backport of ec08d62a20 from master

Note: See TracTickets for help on using tickets.
Back to Top