2. One-to-Many (1:N) Relationships

This is a real example which illustrates a one-to-many relationship between one Location and many Devices.

From Device.py


...
from Products.ZenRelations.RelSchema import *
...
class Device(ManagedEntity, Commandable):
...
event_key= portal_type = meta_type = 'Device'

default_catalog= "deviceSearch" #device ZCatalog

relationshipManagerPathRestriction = '/Devices'
...
_relations = ManagedEntity._relations + (
("location", ToOne(ToMany, "Location", "devices")),
)
...

From Location.py


...
from Products.ZenRelations.RelSchema import * 

1

...
class Location(DeviceOrganizer):
...
# Organizer configuration
dmdRootName = "Locations"

portal_type = meta_type = event_key = 'Location'

_relations

2
 = DeviceOrganizer._relations + (
("devices" 

3
, ToMany(ToOne,"Device","location")),

4

)
...

According to this relationship there can be only one Location assigned to a Device but more than one Device assigned to a Location. This relationship is created by:

1

Importing ToOne and ToMany from Products.ZenRelations.RelSchema.

2

Appending a two-item tuple to the _relations attribute

3

The first item in the tuple is a "string" object which is the local name

4

The second item in the tuple is a "RelSchema" object which represents the relationship to another class.

RelSchema constructors takes 3 parameters:

  • The first parameter is a "type" object, "remoteType" which represents the relationship from another class. The "type" should be of a class derived from RelSchema

  • The second parameter is a "string" object, "remoteClass" which is the class name of the relative.

  • The third parameter is a "string" object, "remoteName" which the remote name of itself.

    Appending a complementary two item tuple to the _relations attribute in the relative class.