#Surprising behavior: "reverse" attribute for OneToOneField *vanishes* instead of being set to None

16 messages · Page 1 of 1 (latest)

formal shoal
#

This is best described by a tiny example: https://gitlab.com/offby1/django-tutorial/-/tree/8da79f6bab5edd98a33292a4370b9afee8e73b3b

If you clone that, and run poetry install --no-root, and then DJANGO_SETTINGS_MODULE=django_project.settings poetry run pytest demo/tests.py --create-db, you'll see the test fail.

My question is: why does it behave that way? Why doesn't the test pass? Is this behavior documented somewhere?

#

Because of this behavior, I find myself writing getattr(t, "bottle", None) more than I'd like to.

glass hollow
#

maybe try .save()

glass hollow
#

I would check whether the objects have been created

trim kernel
#

Does it make a difference if you explicitly set the related name?

formal shoal
#

gosh I hadn't noticed any of these replies!

formal shoal
glass hollow
formal shoal
#

didn't help

#

so I'm not saying that the behavior is wrong; I'm saying it's surprising.

ember flame
#

if you "assert t.bottle is None" on line 6, before you create b, you will get the same exception that happens after b is deleted.

formal shoal
#

oho

#

indeed. Somehow that's less surprising. Lemme examine my own mind and see if I can articulate why 🙂

#

meanwhile, I'll ask: is there a cleaner way to do stuff with t.bottle than getattr(t, "bottle", None)?

ember flame
#

That's a good question. Using getattr seems easy to read and it will perform consistently and it uses less space than a try..except clause or a assertRaises. As for the "assert t.bottle is None", at least it is behaving consistently. I think that with "null=True" on the OneToOne relationship from Bottle to Thing that it would be reasonable to expect the reverse to be None if there is no relationship. I suppose there is a good reason for throwing an exception instead.