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:
>>> print c1.owner
None
>>> print p1.cars
CarSet([])
The attribute cars
has an empty set.
Now let’s establish a relationship between these two instances:
>>> c1.owner = p1
If we print the values of relationship attributes now, then we’ll see the following:
>>> print c1.owner
Person[1]
>>> print p1.cars
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:
>>> p1 = Person(name='John')
>>> 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.