I’m going through the documentation of One-To-One relationship, and I find the code snippet below to be confusing:
# Set the place using assignment notation. Because place is the primary key on Restaurant, the save will create a new restaurant:
>>> r.place = p2
>>> r.save()
>>> p2.restaurant
<Restaurant: Ace Hardware the restaurant>
>>> r.place
<Place: Ace Hardware the place>
# Set the place back again, using assignment in the reverse direction:
>>> p1.restaurant = r
>>> p1.restaurant
<Restaurant: Demon Dogs the restaurant>
Why do I think that this code is bad?
By performing the set place back operation nothing changes at the database level
The p2.restaurant gets broken: instead of <Restaurant: Ace Hardware the restaurant> it returns
<Restaurant: Demon Dogs the restaurant>
Well, you see Ken, if this amazing feature would be undocumented, I could prevent something like this going into production in a code review, and now my life becomes more complicated. What can a simple mortal developer do against the documented feature?
I’m not sure I’m following what you’re trying to say here.
Your original quote showing the code fragments are actually a combination from multiple separate examples demonstrating different features of the API, with a preface:
What follows are examples of operations that can be performed using the Python API facilities.
Any one of those examples would each be appropriate in their proper context. But I’m not sure how/why you think that just aggregating everything together would be something you’d want to do.
It is not. It’s important to understand (and the example demonstrates) that you can establish the one-to-one relationship between two objects on either object. You do not need to define the relationship using the object defining the OneToOne field.