我是一个Django Rest框架和Django新手,我可以使用随机数据来制作阶段,但我不能使用序列化程序来添加新的阶段。
我的模型和序列化程序
class Stage(models.Model):
class Meta:
db_table = 'stage'
stage_id = models.AutoField(primary_key=True)
stage_name = models.CharField(max_length=64, null=False)
company = models.ForeignKey(
Company,
db_column='id',
on_delete=models.CASCADE,
)
class StageSerializer(ModelSerializer):
stage_id = IntegerField(read_only=True)
class Meta:
model = Stage
fields = [
'stage_id',
'stage_name',
'company',
]
def update(self, instance, validated_data):
pass
def create(self, validated_data):
# create stages
stage = create_stage(**validated_data)
return stageview.py
class StageListAPIView(APIView):
def post(self, request, company_id):
data = request.data.copy()
company = get_company_by_id(company_id)
data['company'] = company.pk
serializer = StageSerializer(data=data)
if not serializer.is_valid(raise_exception=True):
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
new_data = serializer.validated_data
serializer.save(company=company)
return Response(new_data, status=HTTP_200_OK)request.data
<QueryDict: {'stage_name': ['kAkSdKq9Gt'], 'company': [6]}>我将收到错误:TypeError: Object of type Company is not JSON serializable
我无法理解它,也不知道如何使用序列化程序来保存外键。
发布于 2018-12-13 18:31:10
您需要序列化Company实例,然后才能将其包含在StageSerializer中。
一个简单的示例如下所示
class CompanySerializer(ModelSerializer):
class Meta:
model = Company
fields = '__all__'然后将其包含在您的StageSerializer中
class StageSerializer(ModelSerializer):
stage_id = IntegerField(read_only=True)
company = CompanySerializer(source='company', read_only=True)
class Meta:
model = Stage
fields = [
'stage_id',
'stage_name',
'company',
]https://stackoverflow.com/questions/53759469
复制相似问题