From 2f1b42ebf9985b67dc5e0f54ed881c6e68813ee8 Mon Sep 17 00:00:00 2001 From: Vyacheslav Tverskoy Date: Tue, 27 Sep 2016 22:43:34 +0500 Subject: [PATCH] Serialization option to ignore DoesNotExist exception raised from callable fields --- flask_mongorest/resources.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/flask_mongorest/resources.py b/flask_mongorest/resources.py index 9bdc23a6..dba26a58 100644 --- a/flask_mongorest/resources.py +++ b/flask_mongorest/resources.py @@ -8,6 +8,7 @@ from mongoengine.base.proxy import DocumentProxy from mongoengine.fields import EmbeddedDocumentField, ListField, ReferenceField, GenericReferenceField, SafeReferenceField from mongoengine.fields import DictField +from mongoengine.errors import DoesNotExist from cleancat import ValidationError as SchemaValidationError from flask_mongorest import methods @@ -442,7 +443,13 @@ def get(obj, field_name, field_instance=None): # if the field is callable, execute it with `obj` as the param if hasattr(self, field) and callable(getattr(self, field)): - value = getattr(self, field)(obj) + try: + value = getattr(self, field)(obj) + except DoesNotExist: + if kwargs.get('ignore_broken_references', False): + value = None + else: + raise # if the field is associated with a specific resource (via the # `related_resources` map), use that resource to serialize it