DRF文档-动态获取序列化程序

时间:2018-08-14 10:03:32

标签: django-rest-framework documentation

我有一个视图集,该视图集对不同的HTTP方法(甚至可能对不同的用户)使用不同的序列化器。 DRF文档说:

SELECT * FROM performance_schema.host_cache

有人可以给我提供“处理此案的调整”的例子吗?

说我有一个视图集,该序列集将序列化器To be compatible with this behaviour methods (such as get_serializer or get_serializer_class etc.) which inspect self.request or, particularly, self.request.user may need to be adjusted to handle this case. 用于管理员的get方法,将序列化器A用于所有其他用户的get方法,并将序列化器B用于所有其他方法。如何指定它以便文档理解?我正在使用内置的。

我的C

urls.py

1 个答案:

答案 0 :(得分:1)

最小示例
models.py

class SampleModel(models.Model):
    name = models.CharField(max_length=120)
    age = models.IntegerField()
    address = models.CharField(max_length=100)

serializers.py

class SampleSerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = SampleModel


class SampleSerializerCreate(serializers.ModelSerializer):
    age = serializers.IntegerField(max_value=20)

    class Meta:
        fields = '__all__'
        model = SampleModel

views.py

class SampleViewset(ModelViewSet):
    serializer_class = SampleSerializer
    queryset = SampleModel.objects.all()

    def get_serializer_class(self):
        if self.action=='create':
            return SampleSerializerCreate
        return SampleSerializer

在这里,我使用了一种逻辑,即在创建SampleModel时,age属性的最大值不能超过20。

更新1

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'sample', SampleViewset)
urlpatterns = [
                  path('docs/', include_docs_urls(title='My API title', public=True, patterns=router.urls)),

              ] + router.urls