【发布时间】:2017-01-10 12:03:44
【问题描述】:
我有一个模型,它通过 Django REST 框架作为资源公开。
当在相关端点上执行 POST 请求时,我需要手动创建对象,这就是我使用 generics.ListCreateAPIView 并覆盖 create() 方法的原因。
但是我需要检查 POST 请求的有效负载中给出的参数是否格式正确/现有/等...
我应该在哪里执行此验证,它与序列化程序有什么关系?
我尝试在相关的 Serializer 中编写一个 validate() 方法,但它从未在 POST 请求中调用。
class ProductOrderList(generics.ListCreateAPIView):
model = ProductOrder
serializer_class = ProductOrderSerializer
queryset = ProductOrder.objects.all()
def create(self, request, *args, **kwargs):
data = request.data
# Some code here to prepare the manual creation of a 'ProductOrder' from the data
# I would like the validation happens here (or even before)
po = ProductOrder.objects.create(...)
class ProductOrderSerializer(serializers.ModelSerializer):
class Meta:
model = ProductOrder
def validate(self, data): # Never called
# Is it the good place to write the validator ??
【问题讨论】:
标签: django validation django-rest-framework