REST框架中单个模型的多个端点

时间:2018-10-05 17:52:26

标签: django-rest-framework

我有一个用于多页表单的REST框架应用程序:

(a*b*)*

我正在尝试为模型中的两个数据块的每一个创建端点:

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)

我希望端点看起来像这样:

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)

但是我不确定如何构造视图以实现此目的。目前,我正在使用模型视图集:

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

一个模型可以有两个序列化器吗?

1 个答案:

答案 0 :(得分:1)

对于一个模型,当然可以有2个(或任意数量)序列化器。而且您走在正确的道路上。您想要的是将不同的URL映射到不同的视图。因此,就您而言,它可能类似于以下内容:

请注意,我已将您的每个序列化器转换为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')

接下来,我们有2个不同的URL指向2个不同的视图:

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
]

最后,视图本身(为了方便起见,我使用通用的RetrieveAPIView

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