我想通过 django-rest-framework 将发送的 json 数据保存到 db。问题是,不保存关系并返回错误。
下面的片段是我的模型:
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE)
name = models.CharField(max_length=30)
family = models.CharField(max_length=50)
class Klass(models.Model):
title = models.CharField(max_length=50)
description = models.CharField(max_length=500)
teacher = models.ForeignKey(Profile, related_name='teacher', on_delete=models.CASCADE)
我使用下面的序列化程序来序列化/反序列化Klass
模型。
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('pk', 'name', 'family')
class KlassSerializer(serializers.ModelSerializer):
teacher = ProfileSerializer()
class Meta:
model = Klass
fields = ('id', 'title', 'description', 'teacher')
现在,当我准备一个 JSON 对象并将其发送到视图时,它会返回错误。下面是视图类:
class KlassView(APIView):
"""for SELECT, INSERT Queries"""
def get(self, request, pk):
# somthing
@csrf_exempt
def post(self,request, pk=None):
"""For Creating A Class"""
serializer = KlassSerializer(data=request.data)
if serializer.is_valid():
teacher = ProfileSerializer(request.data['teacher']['pk'])
serializer.teacher = teacher.data
serializer.save()
return Response({'data': serializer.data})
else:
return Response({'data': serializer.errors})
错误是:
该
.create()
方法默认不支持可写嵌套字段。.create()
为 serializer编写显式方法mainp.serializers.KlassSerializer
,或read_only=True
在嵌套的序列化器字段上设置。
如何保存关系KlassSerializer
以保存到数据库?