Toby
Toby

Reputation: 13385

Multiple endpoints for a single model in REST framework

I have a REST framework app for a multi-page form:

class InformationRequest(models.Model):
  # user information
  first_name = models.CharField(max_length=60)
  last_name = models.CharField(max_length=60)
  # contact details
  phone = models.CharField(max_length=60)
  email = models.CharField(max_length=60)

I'm trying to create endpoints for each of the two blocks of data within the model:

UserInformationSerializer(serializers.Serializer):
  first_name = serializers.CharField(max_length=60)
  last_name = serializers.CharField(max_length=60)

ContactDetailsSerializer(serializers.Serializer):
  phone = serializers.CharField(max_length=60)
  email = serializers.CharField(max_length=60)

I'd like the endpoints to look like:

requests/1/user-informtion
requests/1/contact-details

But I'm unsure of how to structure the view to achieve this. Currently I'm using a model viewset:

class InformationRequestViewSet(viewsets.ModelViewSet):
    queryset = InformationRequest.objects.all()
    serializer_class = ??

Is it possible to have two serializers for one model?

Upvotes: 0

Views: 928

Answers (1)

slider
slider

Reputation: 12990

It's certainly possible to have 2 (or any number of) serializers for a model. And you are on the right path. What you want is different urls mapping to different views. So in your case, it can be something like the following:

Note that I turned each of your serializers into a ModelSerializer.

path-to/serializers.py

class UserInformationSerializer(serializers.ModelSerializer):
    class Meta:
        model = InformationRequest
        fields = ('first_name', 'last_name')

class ContactDetailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = InformationRequest
        fields = ('phone', 'email')

Next, we have 2 different urls that point to 2 different views:

path-to/urls.py

urlpatterns = [
    url(r'^requests/(?P<pk>\d+)/user-information/$', views.UserInformationDetail.as_view()),
    url(r'^requests/(?P<pk>\d+)/contact-details/$', views.ContactInformationDetail.as_view()),
# ... other urls
]

And finally, the views themselves (I'm using generic RetrieveAPIView for convenience)

path-to/views.py

class UserInformationDetail(generics.RetrieveAPIView):
    queryset = InformationRequest.objects.all()
    serializer_class = UserInformationSerializer

class ContactInformationDetail(generics.RetrieveAPIView):
    queryset = InformationRequest.objects.all()
    serializer_class = ContactDetailsSerializer

Upvotes: 1

Related Questions