Ben
Ben

Reputation: 198

Django REST framework HyperlinkedModelSerializer

I'm working on streamlining how I include different models in the API for my Djangp app. Previously I had it set it where each model had a Viewset and a Serializer separately defined for it. Instead I'm working on a more generic method whereby I just pass in a Model and a list of relevant fields, and will be added to the API automatically. The problem I'm running in to currently is with defining the serializer_class:

from myapp import MyModel
from rest_framework.serializers import HyperlinkedModelSerializer
from rest_framework.viewsets import ModelViewSet

app_name = 'myapp'
fields = ('field1', 'field2', 'field3')
queryset = MyModel.objects.all()

# Problem is here
serializer_class = HyperlinkedModelSerializer(model=MyModel, fields=fields)
viewset = ModelViewSet(queryset=queryset, serializer_class=serializer_class)

# Then to register it all with the router:
self.register(app_name + '/' +  model.__name__, viewset)

I get the error:

TypeError: __init__() got an unexpected keyword argument 'fields'

The problem seems to be that in HyperlinkedModelSerializer, 'model' and 'fields' are normally defined as Meta options so it doesn't seem to accept them when they are provided in this way.

Is there a way to achieve this?

Thanks.

Upvotes: 0

Views: 818

Answers (1)

Linovia
Linovia

Reputation: 20966

You could probably define a specific init with a lot of weird things or declare your class on the fly with type:

MyMeta = type(
    'Meta',
    [],
    {"model": MyModel, "fields": fields},
)
MyHyperlinkedModelSerializer = type(
    'MyHyperlinkedModelSerializer',
    (HyperlinkedModelSerializer,),
    {'Meta': MyMeta},
)
viewset = ModelViewSet(
    queryset=queryset,
    serializer_class= MyHyperlinkedModelSerializer,
)

Upvotes: 0

Related Questions