Relations#

You can model relationships between content items by placing them in a hierarchy. For example, a folder speakers could contain the (folderish) speakers. Each speaker would contain their talks. Or speakers could be linked to each other in rich text 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.

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 thing.

Controlling relation targets#

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

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

Configure the relations widget#

Note

These settings only have an effect in Plone 6 Classic UI.

RelatedItemsFieldWidget is the Python class of the default widget used by relation fields.

With pattern_options you can further configure the widget.

In the following example, you can specify pattern_options:

  • where to start browsing using the basePath, and

  • whether to leave the select menu 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 example, 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={
14        "basePath": make_relation_root_path,
15    }
16)

Using the search mode of the relations widget#

Note

These settings only have an effect in Plone 6 Classic UI.

So far we only used the vocabulary plone.app.vocabularies.Catalog, which returns the full content tree. Alternatively you can use CatalogSource to specify a catalog query that only returns the values from the query.

You can pass to CatalogSource the same arguments you use for catalog queries. This makes it very flexible for limiting relatable items by type, path, date, and other items.

Setting the mode of the widget to search makes it easier to select from the content that results from your catalog query instead of having to navigate through your content tree.

The problem is that, in the default mode of the relations widget, items that are in containers are not shown unless you add these types of containers to the query.

Therefore, it is recommended to use CatalogSource only in search mode.

 1from plone.app.vocabularies.catalog import CatalogSource
 2
 3speakers = RelationList(
 4    title="Speaker(s) for this talk",
 5    value_type=RelationChoice(source=CatalogSource(portal_type="speaker")),
 6    required=False,
 7)
 8directives.widget(
 9    "speakers",
10    RelatedItemsFieldWidget,
11    pattern_options={
12        "baseCriteria": [  # This is an optimization that limits the catalog query
13            {
14                "i": "portal_type",
15                "o": "plone.app.querystring.operation.selection.any",
16                "v": ["speaker"],
17            }
18        ],
19        "mode": "search",
20    },
21)
Seach mode of RelationWidget

Search mode of RelationWidget#

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 complete 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        )

Create relation fields through the web or in XML#

You can create relation fields through the web and edit their XML.

  • Using the Dexterity schema editor, add a new field and select Relation List or Relation Choice for its Field type, depending on whether you want to relate to multiple items or a single item.

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

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>

Using different widgets for relations#

Often the standard widget for relations is not what you want. It can be hard to navigate to the content to which you want to relate, and the search mode of the default widget is not suitable for all use cases.

If you want to use checkboxes, radio buttons, or a select menu, 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        {"portal_type": ["Document", "Event"]}
10    ),
11    required=False,
12)
13directives.widget(
14    "relationchoice_field_select",
15    SelectFieldWidget,
16)

The field should then look like this:

RelationChoice field with select widget

RelationChoice 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            title_template="{brain.Type}: {brain.Title} at {path}",  # Custom item rendering!
11        )
12    ),
13    required=False,
14)
15directives.widget(
16    "relationlist_field_ajax_select",
17    AjaxSelectFieldWidget,
18    pattern_options={  # Some options for Select2
19        "minimumInputLength": 2,  # Don't query until at least two characters have been typed
20        "ajax": {"quietMillis": 500},  # Wait 500ms after typing to make query
21    },
22)
Relationlist Field with AJAXSelect

Relationlist Field with AJAXSelect#

Inspecting relations#

In Plone 6 Classic UI, you can inspect all relations and back relations in your site using the control panel Relations at the browser path /@@inspect-relations.

The Relations controlpanel

The Relations controlpanel#

In Plone 5 this is available through the add-on collective.relationhelpers.

Programming with relations#

Plone 6#

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

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.

Plone 5.2 and older#

In older Plone versions, you can use collective.relationhelpers to create and read relations and back relations in a very similar way.

REST API#

A REST API endpoint to create, read, and delete relations and back relations will be part of plone.restapi. See https://github.com/plone/plone.restapi/issues/1432.

Relation fields without relations#

A light-weight alternative to using relations is to store a UUID of the object to which you want to link. Obviously you will lose 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 because you cannot store RelationValue objects in the registry.

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 storage optimized for the queries needed. zc.relation is sort of an outlier with regard 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 automatically 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 that 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 data manager gets another unique ID from the IntId utility.

  5. The same data manager 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 using delattr(rel.from_object, rel.from_attribute). This is a terrible idea. 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 called 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.

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 are not used. Instead, they are from and to. Thus the API for getting the target uses:

  • 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, for example, through link integrity relations (isReferencing) or the relation between a working copy and the original (iterate-working-copy).