#22048 closed Cleanup/optimization (fixed)
Document ways of checking for OneToOneField
Reported by: | Daniele Procida | Owned by: | code22 |
---|---|---|---|
Component: | Documentation | Version: | dev |
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 by , 11 years ago
Triage Stage: | Unreviewed → Accepted |
---|---|
Type: | Uncategorized → Cleanup/optimization |
comment:2 by , 11 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
comment:3 by , 11 years ago
comment:6 by , 11 years ago
Has patch: | set |
---|
comment:7 by , 11 years ago
Resolution: | → fixed |
---|---|
Status: | assigned → closed |
pull request for this ticket: https://github.com/django/django/pull/2356