在DRF中创建发布请求时如何限制字段?

时间:2019-11-26 17:04:55

标签: django-rest-framework

我正在使用DRF制作POST api。在该api中,我只需要几个字段(名称,大小,customer_name,customer_address),但不需要此字段(status,ordered_time),因为我想在运行时将这些字段保存为status ='open', ordered_time = DateTimeField.now()

views.py

class PizzaOrderCustomerView(APIView):   
    def post(self, request):
        orders = request.data.get('orders')
        # Create an article from the above data
        serializer = ArticleSerializer(data=orders)
        if serializer.is_valid(raise_exception=True):
            article_saved = serializer.save()
        return Response({"success": "Article '{}' created successfully".format(article_saved.name)})

models.py

class PizzaOrder(models.Model):
    name = models.CharField(max_length=120)
    size = models.CharField(max_length=10, choices=SIZE_CHOICE, default='MEDIUM')
    customer_name = models.CharField(max_length=120)
    customer_address = models.TextField()
    ordered_time = models.DateTimeField(default=timezone.now, editable=False)
    status = models.CharField(max_length=20, default='open', editable=False)

serializers.py

class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = PizzaOrder
        # fields = '__all__'
        read_only_fields = ('status',)

但是当我尝试创建订单时,它也需要状态和ordered_time。但是它应该在自动创建订单时保存。 提出一个好的方法。

1 个答案:

答案 0 :(得分:1)

from rest_framework import viewsets, mixins


class PizzaViewsets(viewsets.ViewSet, mixins.CreateModelMixin):
    model = PizzaOrder
    serializer_class = OrderSerializer
    queryset = model.objects.all(

序列化器,最好总是提及所有字段而不是 全部

class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = PizzaOrder
        fields = ('status','ordered_time','name', 'size', 'customer_name', 'customer_address',)
        read_only_fields = ('status','ordered_time',)