如何通过邮递员在drf发布请求中发布列表

时间:2020-09-12 11:21:18

标签: django django-rest-framework postman

我有一个可以有多个电话号码的客户模型,就像一个人可以有多个电话号码一样。 我想在数据库中创建一个客户端,并同时添加其所有电话号码。就像一个人以表格形式提交数据一样。

现在我在邮递员中测试我的API,但是当在序列化程序中添加数字字段,GET请求正在工作但可以为邮递工作时,我可以提交数据

models.py

class Client(models.Model):
    name = models.CharField(max_length=32)
    departure = models.DateTimeField(default=None, blank=True)
    arrival = models.DateTimeField(default=None, blank=True)
    price = models.IntegerField(validators=[MinValueValidator(0)])

    def __str__(self):
        return self.name



class Number(models.Model):
    number = models.IntegerField()
    client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True, related_name='number')

serializers.py

class NumberSerializer(serializers.ModelSerializer):
    class Meta:
        model = Number
        fields = ('id', 'number')

class ClientSerializer(serializers.ModelSerializer):
    number = NumberSerializer(many=True)
    class Meta:
        model = Client
        fields = ('id', 'name', 'departure', 'arrival', 'price','number')

views.py

class ClientViewSet(viewsets.ModelViewSet):
    queryset = Client.objects.all()
    serializer_class = ClientSerializer
    authentication_classes = (TokenAuthentication, )
    permission_classes = (IsAuthenticated,)

这就是我通过邮递员发出发帖请求并出现错误的方式

postman post request parameters and error

2 个答案:

答案 0 :(得分:0)

enter image description here,您必须发送json而不是表单数据you have to send in json instead of form-data

答案 1 :(得分:0)

我认为您需要重写create方法来制作writable nested serializer

class NumberSerializer(serializers.ModelSerializer):
    class Meta:
        model = Number
        fields = ('id', 'number')

class ClientSerializer(serializers.ModelSerializer):
    number = NumberSerializer(many=True)
    class Meta:
        model = Client
        fields = ('id', 'name', 'departure', 'arrival', 'price','number')
    
    def create(self, validated_data):
        number_data = validated_data.pop('number')
        number = Number.objects.create(**number_data)
        client = Client.objects.create(number=number, **validated_data)
        return client