Support a related_default on OneToOne fields
|Reported by:||rvdrijst||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||master|
|Severity:||Normal||Keywords:||onetoone related expection null|
|Cc:||rvdrijst, eallik@…, olau@…, django@…, sebastian, aaugustin, cvrebert, frankoid, mike@…||Triage Stage:||Accepted|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Description (last modified by aaugustin)
EDIT: scroll to comment 13 to see what this ticket is about.
Referencing a OneToOneField with null=True (i.e. it's optional) when there is no value set will return None, as expected.
However, referencing the reverse side of the relation does not follow this behavior and raises a DoesNotExist exception.
For example, in the following situation where Shops have optionally a Place (e.g. webshops need not have a physical location):
class Place(models.Model) address = models.CharField(max_length=80) class Shop(models.Model) place = models.OneToOneField(Place, null=True) name = models.CharField(max_length=50) website = models.URLField()
This does work as expected:
>>> s1 = Shop.objects.create(name='Shop', website='shop.com') >>> print s1.place None
But this doesn't work as expected:
>>> p1 = Place.objects.create(address='123 somestr') >>> p1.shop ... [exception stack trace] ... DoesNotExist: Shop matching query does not exist.
I would expect this to be None when null is allowed on the OneToOneField.
Please correct my if I'm wrong.
I have attached a patch to fix this (checking if null is allowed and returning None or raising the exception appropriately), including tests.
Unfortunately this is slightly backwards incompatible, since someone may currently rely on the exception being thrown.
Change History (30)
Changed 6 years ago by rvdrijst
comment:2 Changed 6 years ago by jacob
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Triage Stage changed from Unreviewed to Design decision needed
comment:12 Changed 4 years ago by SmileyChris
- milestone 1.3 deleted
- Severity set to Normal
- Type set to Bug
comment:13 Changed 4 years ago by lukeplant
- Easy pickings unset
- Has patch unset
- Triage Stage changed from Design decision needed to Accepted
- Type changed from Bug to New feature
comment:23 Changed 3 years ago by aaugustin
- Summary changed from OneToOne fields with null=True raise DoesNotExist exception on related model to Support a related_default on OneToOne fields