我有一个可以有多个电话号码的客户模型,就像一个人可以有多个电话号码一样。 我想在数据库中创建一个客户端,并同时添加其所有电话号码。就像一个人以表格形式提交数据一样。
现在我在邮递员中测试我的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,)
这就是我通过邮递员发出发帖请求并出现错误的方式
答案 0 :(得分:0)
答案 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