rsinger86 / drf-flex-fields

Dynamically set fields and expand nested resources in Django REST Framework serializers.
MIT License
740 stars 61 forks source link

Support lazily evaluating expanded serializer class from a function #138

Open seaworn opened 9 months ago

seaworn commented 9 months ago

While lazily evaluating the expanded serializer class from a string caters for avoiding circular imports, I need a way to evaluate the class from a function.

I'm using this package together with django-oscar-api which provides it's own helper function (get_api_class) for dynamically loading classes so as to allow overriding the default serializers. As such, I would like to be able to define an expandable field like this:

expandable_fields = {"orders": (lambda: get_api_class("serializers.checkout", "OrderSerializer"), {"many": True})}

I imagine this could provide a lot more flexibility allowing executing some logic to determine the serializer class (or import path), even outside of django-oscar-api

I did some customizing here to get this working and would be happy to open a PR if you're willing to support this in this package