Skip to content

Commit

Permalink
Fix invalid values in RelationListFieldSerializer. (#1818)
Browse files Browse the repository at this point in the history
* Fix invalid values in serializer.

* Add test to check deleted relations

* use to_id attribute to check content's existance.
  • Loading branch information
Faakhir30 authored Oct 2, 2024
1 parent 6e5e669 commit f68fab7
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
1 change: 1 addition & 0 deletions news/1818.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix response of `RelationListFieldSerializer` by filtering out invalid items. @Faakhir30
14 changes: 13 additions & 1 deletion src/plone/restapi/serializer/relationfield.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,16 @@ class RelationChoiceFieldSerializer(DefaultFieldSerializer):
@adapter(IRelationList, IDexterityContent, Interface)
@implementer(IFieldSerializer)
class RelationListFieldSerializer(DefaultFieldSerializer):
pass
def get_value(self, default=[]):
"""Return field value reduced to list of non-broken Relationvalues.
Args:
default (list, optional): Default field value. Defaults to empty list.
Returns:
list: List of RelationValues
"""
value = super().get_value()
if not value:
return []
return [el for el in value if el.to_id]
28 changes: 28 additions & 0 deletions src/plone/restapi/tests/test_dxcontent_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
from zope.component import provideAdapter
from zope.component import queryUtility
from zope.interface import Interface
from z3c.relationfield import RelationValue
from z3c.relationfield.event import _setRelation
from zope.component import getUtility
from zope.intid.interfaces import IIntIds
from zope.publisher.interfaces.browser import IBrowserRequest
from importlib import import_module

Expand Down Expand Up @@ -191,6 +195,30 @@ def test_serializer_includes_expansion(self):
"foo",
)

def test_serializer_excludes_deleted_relations(self):

intids = getUtility(IIntIds)
self.portal.invokeFactory(
"DXTestDocument",
id="doc2",
)
rel1 = RelationValue(intids.getId(self.portal.doc1))
rel2 = RelationValue(intids.getId(self.portal.doc2))
self.portal.doc1.test_relationlist_field = [
rel1,
rel2,
]
_setRelation(self.portal.doc1, "test_relationlist_field", rel1)
_setRelation(self.portal.doc1, "test_relationlist_field", rel2)
# delete doc2 to make sure we have a None value in the relation list
self.portal.manage_delObjects(["doc2"])

obj = self.serialize()
self.assertEqual(1, len(obj["test_relationlist_field"]))
self.assertEqual(
"http://nohost/plone/doc1", obj["test_relationlist_field"][0]["@id"]
)

def test_get_is_folderish(self):
obj = self.serialize()
self.assertIn("is_folderish", obj)
Expand Down

0 comments on commit f68fab7

Please sign in to comment.