When a type has field with the value strawberry.UNSET
, calling strawberry.asdict
in the value gets you a dict where that value has None
. The expected behavior is that the field is not present in the resulting dict.
This is code that I wrote to circunvent the issue:
def transform_items_recursively(
input_dict: Dict,
fn: Callable[[str, Any], Optional[Dict]],
) -> Dict:
"""
Apply fn to every key-value in dict, recursively.
"""
modified_dict = {}
for key, value in input_dict.items():
result: Optional[Dict] = None
if isinstance(value, dict):
# If it is a dict, first transform it and then call fn on the key with the new value
result = fn(key, transform_items_recursively(value, fn))
elif isinstance(value, list) and any([isinstance(v, dict) for v in value]):
# If it is a list of dicts, transform each dict in it and build a new list. Finally,
# call fn on the new value.
result = fn(key, [transform_items_recursively(val, fn) for val in value])
else:
result = fn(key, value)
if result is not None:
key, value = result
modified_dict[key] = value
return modified_dict
def remove_unset_values(input_dict):
"""
Recursively remove key-value pairs with strawberry.UNSET values from a dictionary and its nested dictionaries.
"""
def fn(key, value):
if value is strawberry.UNSET:
return None
else:
return key, value
return transform_items_recursively(input_dict, fn)
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too