Files
trustme/core/utils/misc.py

66 lines
2.3 KiB
Python

from rest_framework.exceptions import ValidationError # type: ignore # noqa
from django.utils.translation import gettext as _
def get_context_field(field_name: str, data: dict[str, object]) -> dict[str, object]:
"""
Extracts a specified field or its ID variant from a DRF context-like data dictionary.
This utility function is intended to simplify extraction of contextual values (typically
passed through DRF serializer `context`) and enforce that at least one of the required
keys is present:
- `<field_name>`
- `<field_name>_id`
The function returns a dictionary containing whichever key is found. If neither key is
present in the given data, a `ValidationError` is raised with an informative message.
This is especially useful in DRF serializers or views where context-dependent values
are passed and must be validated before use.
Parameters:
----------
field_name : str
The base name of the expected field (e.g., "user", "contract", etc.).
data : dict[str, object]
A dictionary representing the context or other data source to extract from.
Typically, this would be `self.context` from a DRF serializer.
Returns:
-------
dict[str, object]
A dictionary containing one of the following key-value pairs:
{field_name: data[field_name]}
or
{field_name + "_id": data[field_name + "_id"]}
Raises:
------
rest_framework.exceptions.ValidationError
If neither `{field_name}` nor `{field_name}_id` is found in the provided data.
Example:
-------
>>> get_context_field("user", {"user": user_instance})
{'user': <User object>}
>>> get_context_field("organization", {"organization_id": 42})
{'organization_id': 42}
>>> get_context_field("group", {})
ValidationError: Missing required context key: either 'group' or 'group_id'
"""
if field_name in data:
return {field_name: data[field_name]}
field_id = f"{field_name}_id"
if field_id in data:
return {field_id: data[field_id]}
raise ValidationError(
_(
"Missing required context key: either '{field_name}' or '{field_id}'"
).format(field_name=field_name, field_id=field_id)
)