我有一个视图集,该视图集对不同的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
答案 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