Skip to content

Association fields

Fields for establishing relationships between domain elements, connecting entities and aggregates.

See Association Fields reference for usage examples.

HasOne

HasOne(to_cls: str | type, **kwargs: Any)

Bases: Association

Represents an one-to-one association between an aggregate and its entities.

This field is used to define a relationship where an aggregate is associated with at most one instance of a child entity.

Source code in src/protean/fields/association.py
278
279
280
281
282
283
284
285
286
287
def __init__(self, to_cls: "str | type", **kwargs: Any) -> None:
    super().__init__(**kwargs)

    self._to_cls = to_cls
    self.via: str | None = kwargs.pop("via", None)
    self.change = None

    # Associations are not data fields — they cannot be `required` or `unique`
    self.required = False
    self.unique = False

__set__

__set__(instance: Any, value: Any) -> None

Assign the child entity, or remove it by assigning None.

A dict is turned into an instance of the target entity. The parent's identity is written into the child's link field.

The change is recorded in the parent's _temp_cache as ADDED, UPDATED or DELETED. Replacing the child with a different one, or removing it, also records the old child. The repository reads this record to decide what to persist. Assigning the same unchanged entity records no change.

Removing a child also removes the entities linked under it. The aggregate's invariants are checked after the assignment.

RAISES DESCRIPTION
ValidationError

If the value is not an instance of the target entity.

Source code in src/protean/fields/association.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
def __set__(self, instance: Any, value: Any) -> None:
    """Assign the child entity, or remove it by assigning `None`.

    A dict is turned into an instance of the target entity. The parent's
    identity is written into the child's link field.

    The change is recorded in the parent's `_temp_cache` as `ADDED`,
    `UPDATED` or `DELETED`. Replacing the child with a different one, or
    removing it, also records the old child. The repository reads this record to decide what to persist.
    Assigning the same unchanged entity records no change.

    Removing a child also removes the entities linked under it. The
    aggregate's invariants are checked after the assignment.

    Raises:
        ValidationError: If the value is not an instance of the target
            entity.
    """
    # Accept dictionary values and convert them to Entity objects
    if isinstance(value, dict):
        value = self._target_cls(**value)

    super().__set__(instance, value)

    if value is not None and not isinstance(value, self._target_cls):
        raise _wrong_type_error(self)

    # 1. Preserve parent linkage in child entity
    if value is not None:
        _link_has_one_child(self, instance, value)

    # 2. Determine and store the change in the relationship
    assert self.field_name is not None
    current_value = getattr(instance, self.field_name)
    cache = instance._temp_cache.setdefault(self.field_name, HasOneChanges())
    _record_has_one_change(cache, current_value, value)

    self._set_own_value(instance, value)

    # 3. Go Recursive and remove child entities if they are associated with the old value
    if cache.change == "DELETED":
        _remove_child_associations(cache.old_value)

    _postcheck_root(instance)

as_dict

as_dict(value: Any) -> Any

Return JSON-compatible value of self

Source code in src/protean/fields/association.py
489
490
491
492
def as_dict(self, value: Any) -> Any:
    """Return JSON-compatible value of self"""
    if value is not None:
        return value.to_dict()

HasMany

HasMany(to_cls: str | type, **kwargs: Any)

Bases: Association

Represents a one-to-many association between two entities. This field is used to define a relationship where an aggregate has multiple instances of a chil entity.

PARAMETER DESCRIPTION
to_cls

The class of the target entity.

TYPE: type

**kwargs

Additional keyword arguments to be passed to the base field class.

TYPE: Any DEFAULT: {}

Source code in src/protean/fields/association.py
278
279
280
281
282
283
284
285
286
287
def __init__(self, to_cls: "str | type", **kwargs: Any) -> None:
    super().__init__(**kwargs)

    self._to_cls = to_cls
    self.via: str | None = kwargs.pop("via", None)
    self.change = None

    # Associations are not data fields — they cannot be `required` or `unique`
    self.required = False
    self.unique = False

__set__

__set__(instance: Any, value: Any) -> None

This supports direct assignment of values to HasMany fields, like: order.items = [item1, item2, item3]

Source code in src/protean/fields/association.py
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
def __set__(self, instance: Any, value: Any) -> None:
    """This supports direct assignment of values to HasMany fields, like:
    `order.items = [item1, item2, item3]`
    """
    value = value if isinstance(value, list) else [value]

    # Accept dictionary values and convert them to Entity objects
    values = []
    for item in value:
        if isinstance(item, dict):
            values.append(self._target_cls(**item))
        else:
            values.append(item)

    super().__set__(instance, values)

    if value is not None:
        # Ensure cache is initialized before add() tries to read via getattr().
        # Without this, getattr triggers __get__ which falls back to a DB query,
        # failing for event-sourced aggregates that have no database tables.
        try:
            self.get_cached_value(instance)
        except KeyError:
            self.set_cached_value(instance, [])
        self.add(instance, values)

add

add(instance: Any, items: Any) -> None

Add one or more child entities to the parent.

Available on the parent as add_<field name>.

An entity whose identity is not yet linked is recorded as added. A linked entity that is persisted and changed is recorded as updated. Both are recorded in the parent's _temp_cache, which the repository reads to decide what to persist. The parent's identity is written into each child's link field. Passing an empty list removes every current child. The aggregate's invariants are checked before and after the change.

PARAMETER DESCRIPTION
instance

The parent entity.

TYPE: BaseEntity

items

The child entity or entities to add.

TYPE: list | BaseEntity

RAISES DESCRIPTION
ValidationError

If an item is not an instance of the target entity.

Source code in src/protean/fields/association.py
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
def add(self, instance: Any, items: Any) -> None:
    """Add one or more child entities to the parent.

    Available on the parent as `add_<field name>`.

    An entity whose identity is not yet linked is recorded as added. A
    linked entity that is persisted and changed is recorded as updated.
    Both are recorded in the parent's `_temp_cache`, which the repository
    reads to decide what to persist. The parent's identity is written into
    each child's link field. Passing an empty list removes every current
    child. The aggregate's invariants are checked before and after the
    change.

    Args:
        instance (BaseEntity): The parent entity.
        items (list | BaseEntity): The child entity or entities to add.

    Raises:
        ValidationError: If an item is not an instance of the target
            entity.
    """
    super().__set__(instance, items)

    # Pre-check invariants before mutation
    _precheck_root(instance)

    assert self.field_name is not None
    data = getattr(instance, self.field_name)

    # Convert a single item into a list of items, if necessary
    items = [items] if not isinstance(items, list) else items

    # Validate that all items are of the same type, and the correct type
    _check_item_types(self, items)

    entity_id_name = _id_field_name(self._target_cls)
    instance_id_name = _id_field_name(instance)

    current_value_ids = [getattr(value, entity_id_name) for value in data]

    # Remove items when set to empty
    if len(items) == 0 and len(current_value_ids) > 0:
        self.remove(instance, data)

    # Re-read from cache after potential removal so new_data reflects
    # the post-remove state instead of the stale `data` reference.
    try:
        cached = self.get_cached_value(instance)
        new_data = list(cached) if isinstance(cached, list) else [cached]
    except KeyError:
        new_data = list(data)

    cache = instance._temp_cache.setdefault(self.field_name, HasManyChanges())
    for item in items:
        identity = getattr(item, entity_id_name)
        # Items to add
        if identity not in current_value_ids:
            # If the same item is added multiple times, the last item added will win
            cache.added[identity] = item
            _link_has_many_child(self, instance, item, instance_id_name)
            new_data.append(item)
        # Items to update
        elif (
            identity in current_value_ids
            and item.state_.is_persisted
            and item.state_.is_changed
        ):
            _link_has_many_child(self, instance, item, instance_id_name)
            cache.updated[identity] = item

            # Replace updated item in the working copy
            _replace_by_identity(new_data, item, entity_id_name, identity)

    # Update cache with complete item list instead of deleting it.
    # This ensures items are immediately visible via __get__ without
    # requiring a DB round-trip, which is essential for event-sourced
    # aggregates that have no database tables.
    self.set_cached_value(instance, new_data)

    _postcheck_root(instance)

remove

remove(instance: Any, items: Any) -> None

Available as remove_<HasMany Field Name> method on the entity instance.

Remove one or more linked entities from the source entity.

We also recursively remove child entities if they are associated with the removed value.

PARAMETER DESCRIPTION
instance

The source entity instance.

TYPE: BaseEntity

items

The linked entity or entities to be removed.

TYPE: list | BaseEntity

Source code in src/protean/fields/association.py
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
def remove(self, instance: Any, items: Any) -> None:
    """
    Available as `remove_<HasMany Field Name>` method on the entity instance.

    Remove one or more linked entities from the source entity.

    We also recursively remove child entities if they are associated with the removed value.

    Args:
        instance (BaseEntity): The source entity instance.
        items (list | BaseEntity): The linked entity or entities to be removed.
    """
    # Pre-check invariants before mutation
    _precheck_root(instance)

    assert self.field_name is not None
    data = getattr(instance, self.field_name)

    # Convert a single item into a list of items, if necessary
    items = [items] if not isinstance(items, list) else items

    # Validate that all items are of the same type, and the correct type
    _check_item_types(self, items)

    entity_id_name = _id_field_name(self._target_cls)

    current_value_ids = [getattr(value, entity_id_name) for value in data]

    cache = instance._temp_cache.setdefault(self.field_name, HasManyChanges())
    removed_ids: set[Any] = set()
    for item in items:
        identity = getattr(item, entity_id_name)
        if identity in current_value_ids and identity not in cache.removed:
            cache.removed[identity] = item
            removed_ids.add(identity)

        # Remove child entities
        _remove_child_associations(item)

    # Update cache with items remaining after removal instead of deleting it.
    if removed_ids:
        new_data = [
            item
            for item in data
            if getattr(item, entity_id_name) not in removed_ids
        ]
        self.set_cached_value(instance, new_data)

    _postcheck_root(instance)

as_dict

as_dict(value: Any) -> list[Any]

Return JSON-compatible value of self.

PARAMETER DESCRIPTION
value

The value to be converted to a JSON-compatible format.

TYPE: list

RETURNS DESCRIPTION
list

A list of dictionaries representing the linked entities.

TYPE: list[Any]

Source code in src/protean/fields/association.py
719
720
721
722
723
724
725
726
727
728
729
def as_dict(self, value: Any) -> list[Any]:
    """
    Return JSON-compatible value of self.

    Args:
        value (list): The value to be converted to a JSON-compatible format.

    Returns:
        list: A list of dictionaries representing the linked entities.
    """
    return [item.to_dict() for item in value]

get

get(instance: Any, **kwargs: Any) -> Any

Fetch a single linked entity based on the provided criteria.

Available as get_one_from_<HasMany Field Name> method on the entity instance.

PARAMETER DESCRIPTION
**kwargs

The filtering criteria.

TYPE: Any DEFAULT: {}

Source code in src/protean/fields/association.py
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
def get(self, instance: Any, **kwargs: Any) -> Any:
    """Fetch a single linked entity based on the provided criteria.

    Available as `get_one_from_<HasMany Field Name>` method on the entity instance.

    Args:
        **kwargs (Any): The filtering criteria.
    """
    data = self.filter(instance, **kwargs)

    if len(data) == 0:
        raise exceptions.ObjectNotFoundError(
            "No linked entities matching criteria found"
        )

    if len(data) > 1:
        raise exceptions.TooManyObjectsError(
            "Multiple linked entities matching criteria found"
        )

    return data[0]

filter

filter(instance: Any, **kwargs: Any) -> list[Any]

Filter the linked entities based on the provided criteria.

Available as filter_<HasMany Field Name> method on the entity instance.

PARAMETER DESCRIPTION
**kwargs

The filtering criteria.

TYPE: Any DEFAULT: {}

Source code in src/protean/fields/association.py
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
def filter(self, instance: Any, **kwargs: Any) -> list[Any]:
    """Filter the linked entities based on the provided criteria.

    Available as `filter_<HasMany Field Name>` method on the entity instance.

    Args:
        **kwargs (Any): The filtering criteria.
    """
    assert self.field_name is not None
    data = getattr(instance, self.field_name)
    return [
        item
        for item in data
        if all(getattr(item, key) == value for key, value in kwargs.items())
    ]

Reference

Reference(to_cls: str | type, **kwargs: Any)

Bases: FieldCacheMixin, Field

A field representing a reference to another entity. This field is used to establish the reverse relationship to the remote entity.

PARAMETER DESCRIPTION
to_cls

The target entity class or its name.

TYPE: str | type

**kwargs

Additional keyword arguments to be passed to the base Field class.

TYPE: Any DEFAULT: {}

Source code in src/protean/fields/association.py
107
108
109
110
111
def __init__(self, to_cls: "str | type", **kwargs: Any) -> None:
    super().__init__(**kwargs)
    self._to_cls = to_cls

    self.relation = _ReferenceField(self)

linked_attribute property

linked_attribute: str

Return linkage attribute to the target class

This method is initially called from __set_name__() -> get_attribute_name() at which point, the to_cls has not been initialized properly. We simply default the linked attribute to 'id' in that case.

Eventually, when setting value the first time, the to_cls entity is initialized and the attribute name is reset correctly.

get_attribute_name

get_attribute_name() -> str

Return formatted attribute name for the shadow field

Source code in src/protean/fields/association.py
117
118
119
def get_attribute_name(self) -> str:
    """Return formatted attribute name for the shadow field"""
    return self.referenced_as or f"{self.field_name}_{self.linked_attribute}"

get_shadow_field

get_shadow_field() -> tuple[str | None, _ReferenceField]

Return shadow field Primarily used during Entity initialization to register shadow field

Source code in src/protean/fields/association.py
121
122
123
124
def get_shadow_field(self) -> "tuple[str | None, _ReferenceField]":
    """Return shadow field
    Primarily used during Entity initialization to register shadow field"""
    return (self.attribute_name, self.relation)

__get__

__get__(instance: Any, owner: Any) -> Any

Retrieve associated objects

Source code in src/protean/fields/association.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def __get__(self, instance: Any, owner: Any) -> Any:
    """Retrieve associated objects"""
    reference_obj = None
    if hasattr(instance, "state_"):
        try:
            reference_obj = self.get_cached_value(instance)
        except KeyError:
            # Fetch target object by own Identifier
            id_field = self.get_attribute_name()

            id_value = None
            if hasattr(instance, id_field):
                id_value = getattr(instance, id_field)

            if id_value:
                reference_obj = self._fetch_objects(self.linked_attribute, id_value)
                if reference_obj:
                    self._set_own_value(instance, reference_obj)
                else:
                    # No Objects were found in the remote entity with this Entity's ID
                    pass

    return reference_obj

__set__

__set__(instance: Any, value: Any) -> None

Override __set__ to coordinate between relation field and its shadow attribute

Source code in src/protean/fields/association.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def __set__(self, instance: Any, value: Any) -> None:
    """Override `__set__` to coordinate between relation field and its shadow attribute"""
    value = self._load(value)

    if value:
        id_fld = id_field(value)
        assert id_fld is not None
        assert id_fld.field_name is not None
        if getattr(value, id_fld.field_name) is None:
            raise ValueError(
                "Target Object must be saved before being referenced",
                self.field_name,
            )
        else:
            self._set_own_value(instance, value)
            self._set_relation_value(
                instance, getattr(value, self.linked_attribute)
            )
    else:
        self._reset_values(instance)

as_dict

as_dict(value: Any) -> Any

Return JSON-compatible value of self

Source code in src/protean/fields/association.py
257
258
259
def as_dict(self, value: Any) -> Any:
    """Return JSON-compatible value of self"""
    raise NotImplementedError