Django Rest Framework: is it possible to modify a Serializer class at runtime?
django, django-rest-framework
Solution
I found a solution for my problem.
My problem was: I needed to be able to add hyperlinks to other resources without editing the code of a core app. I needed to do it from the code of the additional module.
I wrote this serializer mixin: https://gist.github.com/nemesisdesign/8132696
Which can be used this way:
from myapp.serializers import MyExtensibleSerializer
MyExtensibleSerializer.add_relationship(**{
'name': 'key_name',
'view_name': 'view_name_in_urls_py',
'lookup_field': 'arg_passed_to_to_view_name'
})
Problem
I see I can easily modify the Meta options of a Serializer at run time (i'm not even sure this is the right way to call it, I read around somebody call it monkey patching, even though i don't like it): ``` NodeDetailSerializer.Meta.fields.append('somefield') ``` What if I need to do something like: ``` NodeDetailSerializer.contact = serializers.HyperlinkedIdentityField(view_name='api_node_contact', slug_field='slug') NodeDetailSerializer.Meta.fields.append('contact') ``` Why would I need to do that? I'm trying to build a modular application, I have some optional apps that can be added in an they automatically add some features to the core ones. I would like to keep the code of the two apps separate, also because the additional applications might be moved in a different repository. Writing modular and extensible apps is really a tricky business. Would like to know more about that if anybody has some useful resources to share. Federico