plone / plone.restapi

RESTful API for Plone.
http://plonerestapi.readthedocs.org/
84 stars 73 forks source link

relatedItems field returns None in the serializer if the related item is deleted #1745

Open wesleybl opened 5 months ago

wesleybl commented 5 months ago

Steps to reproduce

  1. Create a content 1
  2. Create a content 2
  3. Edit content 1 and fill in the relatedItems field with content 2
  4. Delete content 2
  5. See content 1 serialization
  6. relatedItems will be: [ None ]

This doesn't make sense to me. In the example, I think it's better to return an empty list. However, to do this, we would have to test the type of each element in a list here, to know if the value is a RelationValue. Or create a new adapter for the IRelationList field

Or should you handle this in the frontend?

ksuess commented 5 months ago

Good catch! The serializers of a RelationList field and RelationChoice field should return only non broken RelationValues. I suggest the following:

@adapter(IRelationList, IDexterityContent, Interface)
@implementer(IFieldSerializer)
class RelationListFieldSerializer(DefaultFieldSerializer):
    def get_value(self, default=None):
        """Return field value reduced to list of non-broken Relationvalues.

        Args:
            default (list, optional): Default field value. Defaults to None.

        Returns:
            list: List of RelationValues
        """
        value = getattr(
            self.field.interface(self.context), self.field.__name__, default
        )
        return [el for el in value if el.to_object]

And accordingly for RelationChoiceFieldSerializer.