One-To-One Relationship

Django v4.2

https://docs.djangoproject.com/en/4.2/topics/db/examples/one_to_one/

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?

  1. By performing the set place back operation nothing changes at the database level
  2. The p2.restaurant gets broken: instead of <Restaurant: Ace Hardware the restaurant> it returns
    <Restaurant: Demon Dogs the restaurant>

The code sample exists to demonstrate the API - don’t try to read anything more into it than that.

It shows that you can define and update a relationship from either side of that relationship.

Would you actually write that full sequence of code in your project? Probably not.

But then most of the examples scattered throughout the docs are not “production ready”. They are illustrations only.

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? :smile:

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.

I’m trying to say that the code snippet in the Set the place back again section looks like an anti-pattern.

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.