Establishing a relationship

Right after we’ve created the instances p1 and c1, they don’t have an established relationship. Let’s check the values of the relationship attributes:

  1. >>> print c1.owner
  2. None
  3. >>> print p1.cars
  4. CarSet([])

The attribute cars has an empty set.

Now let’s establish a relationship between these two instances:

  1. >>> c1.owner = p1

If we print the values of relationship attributes now, then we’ll see the following:

  1. >>> print c1.owner
  2. Person[1]
  3. >>> print p1.cars
  4. CarSet([Car[1]])

When we assigned an owner to the Car instance, the Person.cars relationship attribute reflected the change immediately.

We also could establish a relationship by assigning the relationship attribute during the creation of the Car instance:

  1. >>> p1 = Person(name='John')
  2. >>> c1 = Car(make='Toyota', model='Camry', owner=p1)

In our example the attribute owner is optional, so we can assign a value to it at any time, either during the creation of the Car instance, or later.