39. Relations#

You can model relationships between content items by placing them in a hierarchy (e.g. a folder speakers containing the (folderish) speakers and within each speaker the talks) or by linking them to each other in Richtext fields. But where would you then store a talk that two speakers give together?

Relations allow developers to model relationships between objects without using links or a hierarchy. The behavior plone.app.relationfield.behavior.IRelatedItems provides the field Related Items in the tab Categorization. That field simply says a is somehow related to b.

By using custom relations you can model your data in a much more meaningful way.

39.1. Creating and configuring relations in a schema#

Relate to one item only.

1from z3c.relationfield.schema import RelationChoice
2
3evil_mastermind = RelationChoice(
4    title="The Evil Mastermind",
5    vocabulary="plone.app.vocabularies.Catalog",
6    required=False,
7)

Relate to multiple items.

 1from z3c.relationfield.schema import RelationChoice
 2from z3c.relationfield.schema import RelationList
 3
 4minions = RelationList(
 5    title="Minions",
 6    default=[],
 7    value_type=RelationChoice(
 8        title="Minions",
 9        vocabulary="plone.app.vocabularies.Catalog"
10        ),
11    required=False,
12)

We can see that the code for the behavior IRelatedItems does exactly the same.

39.1.1. Controlling what to relate to#

The best way to control wich item should be relatable to is to configure the widget with directives.widget(). In the following example you can only relate to Documents:

 1from plone.app.z3cform.widget import RelatedItemsFieldWidget
 2
 3relationchoice_field = RelationChoice(
 4    title="Relationchoice field",
 5    vocabulary="plone.app.vocabularies.Catalog",
 6    required=False,
 7)
 8directives.widget(
 9    "relationchoice_field",
10    RelatedItemsFieldWidget,
11    pattern_options={
12        "selectableTypes": ["Document", "Event"],
13    },
14)

39.1.2. Configure the RelatedItemsFieldWidget#

Note

These settings only have a effect in Plone 6 Classic.

With pattern_options you can further configure the widget.

In the following example you can specify a) where to start browsing using the pattern-option basePath and b) to leave the dropdown open using closeOnSelect.

 1relationlist_field = RelationList(
 2    title="Relationlist Field",
 3    default=[],
 4    value_type=RelationChoice(vocabulary="plone.app.vocabularies.Catalog"),
 5    required=False,
 6    missing_value=[],
 7)
 8directives.widget(
 9    "relationlist_field",
10    RelatedItemsFieldWidget,
11    pattern_options={
12        "basePath": ",
13        "closeOnSelect": False,  # Leave dropdown open for multiple selection
14    },
15)

basePath can also be a method. In this exmaple we use the helper-method plone.app.multilingual.browser.interfaces.make_relation_root_path.

 1from plone.app.multilingual.browser.interfaces import make_relation_root_path
 2
 3relationlist_field = RelationList(
 4    title="Relationlist Field",
 5    default=[],
 6    value_type=RelationChoice(vocabulary="plone.app.vocabularies.Catalog"),
 7    required=False,
 8    missing_value=[],
 9)
10directives.widget(
11    "relationlist_field",
12    RelatedItemsFieldWidget,
13    pattern_options=make_relation_root_path,
14)

39.1.4. Define Favorite Locations#

The RelatedItemsFieldWidget allows you to set favorites:

1directives.widget(
2    "minions",
3    RelatedItemsFieldWidget,
4    pattern_options={
5        "favorites": [{"title": "Minions", "path": "/Plone/minions"}]
6    },
7)

favorites can also be a method that takes the current context. Here is a full example as a behavior:

 1from plone import api
 2from plone.app.vocabularies.catalog import CatalogSource
 3from plone.app.z3cform.widget import RelatedItemsFieldWidget
 4from plone.autoform import directives
 5from plone.autoform.interfaces import IFormFieldProvider
 6from plone.supermodel import model
 7from z3c.relationfield.schema import RelationChoice
 8from z3c.relationfield.schema import RelationList
 9from zope.interface import provider
10
11
12def minion_favorites(context):
13    portal = api.portal.get()
14    minions_path = "/".join(portal["minions"].getPhysicalPath())
15    one_eyed_minions_path = "/".join(portal["one-eyed-minions"].getPhysicalPath())
16    return [
17            {
18                "title": "Current Content",
19                "path": "/".join(context.getPhysicalPath())
20            }, {
21                "title": "Minions",
22                "path": minions_path,
23            }, {
24                "title": "One eyed minions",
25                "path": one_eyed_minions_path,
26            }
27        ]
28
29
30@provider(IFormFieldProvider)
31class IHaveMinions(model.Schema):
32
33    minions = RelationList(
34        title="My minions",
35        default=[],
36        value_type=RelationChoice(
37            source=CatalogSource(
38                portal_type=["one_eyed_minion", "minion"],
39                review_state="published",
40            )
41        ),
42        required=False,
43    )
44    directives.widget(
45        "minions",
46        RelatedItemsFieldWidget,
47        pattern_options={
48            "mode": "auto",
49            "favorites": minion_favorites,
50            }
51        )

39.2. RelationFields through the web or in xml#

It is surprisingly easy to create RelationFields through the web

  • Using the Dexterity schema editor, add a new field and select Relation List or Relation Choice, depending on whether you want to relate to multiple items or not.

  • When configuring the field you can even select the content type the relation should be limited to.

When you click on Edit XML field model you will see the fields in the XML schema:

RelationChoice:

1<field name="boss" type="z3c.relationfield.schema.RelationChoice">
2  <description/>
3  <required>False</required>
4  <title>Boss</title>
5</field>

RelationList:

 1<field name="underlings" type="z3c.relationfield.schema.RelationList">
 2  <description/>
 3  <required>False</required>
 4  <title>Underlings</title>
 5  <value_type type="z3c.relationfield.schema.RelationChoice">
 6    <title i18n:translate="">Relation Choice</title>
 7    <portal_type>
 8      <element>Document</element>
 9      <element>News Item</element>
10    </portal_type>
11  </value_type>
12</field>

39.3. Using different widgets for relations#

Todo

Support for StaticCatalogVocabulary in Volto is currently still missing.

Often the standard widget for relations is not what you want since it can be hard to navigate to the content you want to relate to.

If you want to use checkboxes, radiobuttons or a selection-dropdown you need to use StaticCatalogVocabulary instead of CatalogSource to specify your options.

 1from plone.app.vocabularies.catalog import StaticCatalogVocabulary
 2from plone.app.z3cform.widget import SelectFieldWidget
 3from plone.autoform import directives
 4from z3c.relationfield.schema import RelationChoice
 5
 6relationchoice_field_select = RelationChoice(
 7    title="RelationChoice with Select Widget",
 8    vocabulary=StaticCatalogVocabulary(
 9        {
10            "portal_type": ["Document", "Event"],
11            "review_state": "published",
12        }
13    ),
14    required=False,
15)
16directives.widget(
17    "relationchoice_field_select",
18    SelectFieldWidget,
19)

The field should then look like this:

RelationList field with select widget

RelationList field with select widget#

Another example is the AjaxSelectFieldWidget that only queries the catalog for results if you start typing:

 1relationlist_field_ajax_select = RelationList(
 2    title="Relationlist Field with AJAXSelect",
 3    description="z3c.relationfield.schema.RelationList",
 4    value_type=RelationChoice(
 5        vocabulary=StaticCatalogVocabulary(
 6            {
 7                "portal_type": ["Document", "Event"],
 8                "review_state": "published",
 9            }
10        )
11    ),
12    required=False,
13)
14directives.widget(
15    "relationlist_field_ajax_select",
16    AjaxSelectFieldWidget,
17    vocabulary=StaticCatalogVocabulary(
18        {
19            "portal_type": ["Document", "Event", "Folder"],
20        },
21        title_template="{brain.Type}: {brain.Title} at {path}",
22    ),  # Custom item rendering
23    pattern_options={  # Options for Select2
24        "minimumInputLength": 2,  # - Don't query until at least two characters have been typed
25        "ajax": {"quietMillis": 500},  # - Wait 500ms after typing to make query
26    },
27)
Relationlist Field with AJAXSelect

Relationlist Field with AJAXSelect

39.5. Inspecting relations#

You Plone 6 Classic you can inspect all relations and backrelations in your site using the control panel /@@inspect-relations.

The relations controlpanel

The relations controlpanel#

In Plone 5 this is available through the addon collective.relationhelpers.

39.6. Programming with relations#

39.6.1. Plone 6#

Since Plone 6 plone.api has methods to create, read, and delete relations and backrelations.

1from plone import api
2
3portal = api.portal.get()
4source = portal["bob"]
5target = portal["bobby"]
6api.relation.create(source=source, target=target, relationship="friend")
1from plone import api
2
3api.relation.get(source=portal["bob"])
4api.relation.get(relationship="friend")
5api.relation.get(target=portal["bobby"])
1from plone import api
2
3api.relation.delete(source=portal["bob"])

See the chapter Relations of the docs for plone.api for more details.

39.6.2. Plone 5.2 and older#

In older Plone-Versions you can use collective.relationhelpers to create and read relations and backrelations in a very similar way.

39.6.3. Restapi#

A restapi endpoint to create, read, and delete relations and backrelations will be part of plone.restapi. See plone/plone.restapi#1432

39.7. Relationfields without relations#

A light-weight alternative to using relations is to store a UUID of the object you want to link to. Obviously you will loose the option to query the relation-catalog for these but you could create a custom index for that purpose.

The trick is to use Choice and List instead of RelationChoice or RelationList and configure the field to use RelatedItemsFieldWidget:

 1from plone.app.z3cform.widget import RelatedItemsFieldWidget
 2from plone.autoform import directives
 3from zope import schema
 4
 5uuid_choice_field = schema.Choice(
 6    title="Choice field with RelatedItems widget storing uuids",
 7    description="schema.Choice",
 8    vocabulary="plone.app.vocabularies.Catalog",
 9    required=False,
10)
11directives.widget("uuid_choice_field", RelatedItemsFieldWidget)

Again you can use StaticCatalogVocabulary if you want to use alternative widgets. The following example uses Checkboxes:

 1from plone.app.vocabularies.catalog import StaticCatalogVocabulary
 2from plone.autoform import directives
 3from z3c.form.browser.checkbox import CheckBoxFieldWidget
 4from zope import schema
 5
 6uuid_list_field_checkbox = schema.List(
 7    title="RelationList with Checkboxes storing uuids",
 8    vocabulary=StaticCatalogVocabulary(
 9        {
10            "portal_type": "Document",
11            "review_state": "published",
12        }
13    ),
14    required=False,
15)
16directives.widget(
17    "uuid_list_field_checkbox",
18    CheckBoxFieldWidget,
19)

Note

For control panels this is the best way to store relations since you cannot store RelationValue objects in the registry.

39.8. The stack#

Relations are based on zc.relation. This package stores transitive and intransitive relationships. It allows complex relationships and searches along them. Because of this functionality, the package is a bit complicated.

The package zc.relation provides its own catalog, a relation catalog. This is a storage optimized for the queries needed. zc.relation is sort of an outlier with regards to Zope documentation. It has extensive documentation, with a good level of doctests for explaining things.

You can use zc.relation to store the objects and its relations directly into the catalog. But the additional packages that make up the relation functionality don't use the catalog this way.

We want to work with schemas to get auto generated forms. The logic for this is provided by the package z3c.relationfield. This package contains the RelationValue object and everything needed to define a relation schema, and all the code that is necessary to automatically update the catalog.

A RelationValue Object does not reference all objects directly. For the target, it uses an id it gets from the IntId Utility. This id allows direct recovery of the object. The source object stores it directly.

Widgets are provided by plone.app.z3cform and some converters are provided by plone.app.relationfield. The widget that Plone uses can also store objects directly. Because of this, the following happens when saving a relation via a form:

  1. The HTML shows some nice representation of selectable objects.

  2. When the user submits the form, selected items are submitted by their UUIDs.

  3. The Widget retrieves the original object with the UUID.

  4. Some datamanager gets another unique ID from an IntID Tool.

  5. The same datamanager creates a RelationValue from this id, and stores this relation value on the source object.

  6. Some Event handlers update the catalogs.

You could delete a Relation like this delattr(rel.from_object, rel.from_attribute)

This is a terrible idea by the way, because when you define in your schema that one can store multiple RelationValues, your Relation is stored in a list on this attribute.

Relations depend on a lot of infrastructure to work. This infrastructure in turn depends a lot on event handlers being thrown properly. When this is not the case things can break. Because of this, there is a method isBroken which you can use to check if the target is available.

There are alternatives to using Relations. You could instead just store the UUID of an object. But using real relations and the catalog allows for very powerful things. The simplest concrete advantage is the possibility to see what links to your object.

The built-in linkintegrity feature of Plone 5 is also implemented using relations.

39.8.1. RelationValues#

RelationValue objects have a fairly complete API. For both target and source, you can receive the IntId, the object and the path. On a RelationValue, the terms source and target aren't used. Instead, they are from and to. So the API for getting the target is:

  • to_id

  • to_path

  • to_object

In addition, the relation value knows under which attribute it has been stored as from_attribute. It is usually the name of the field with which the relation is created. But it can also be the name of a relation that is created by code, e.g. linkintegrity relations (isReferencing) or the relation between a working copy and the original (iterate-working-copy).