的 Models.py
Article(models.Model):
name=models.CharField(max_length=50)
description=models.TextField(max_length=200)
Characteristic(models.Model):
article=models.OneToOneField(Article,on_delete=models.CASCADE,primary_key=True)
other=models.FloatField()
another=models.IntegerField()
Serializer.py
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model=Article
field='__all__'
class CharacteristicSerializer(serializers.ModelSerializer):
article=serializers.StringRelatedField()
class Meta:
model=Characteristic
field='__all__'
Views.py POST方法(基于API)
def post(self, request,format=None):
serializer=CharacteristicSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
如果我尝试用这样的东西进行POST:
(some_url ...)/ characteristics / other = 4.4 another = 4 post = 1
我收到了下一个错误:
django.db.utils.IntegrityError:(1048,“列'post_id'不能是 空“)
这个想法是接收模型文章的id然后保存模型特征。
有什么想法吗?
答案 0 :(得分:0)
最后我能够解决它。它只是关于字典。
方法POST
def post(self,request,format=None):
serializer=CharacteristicsSerializer(data=request.data)
if serializer.is_valid():
tmp=self.get_article(pk=int(self.request.data['article']))
serializer.save(article=tmp)
return Response(serializer.data,status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
现在它正在发挥作用,如果还有另一种更好的方法可以做到并且有人想要分享它我将会感激