我有这个观点我希望在使用post方法
收回产品ID时在db中保存记录class PeymentAPIView(APIView):
def post(self, request, *args, **kwargs):
serilizer = PeymentSerializer(data=request.data)
if serilizer.is_valid():
serilizer.save(user=request.user,
status=0)
return Response("ok")
else:
#return Response(serilizer.errors)
return Response(status=status.HTTP_400_BAD_REQUEST)
帖子man我用post方法发送这个:
{
"product": 2
}
但我有这个错误,请你告诉我为什么
(1048, "Column 'product_id' cannot be null")
这是我的序列化器:
# product peyment
class PeymentSerializer(ModelSerializer):
product = serializers.SerializerMethodField()
def get_product(self, obj):
return obj.product.product_id
user = serializers.SerializerMethodField()
def get_user(self, obj):
return obj.id
class Meta:
model = Peyment
fields = [
'product',
'status',
'user',
'transfer_id',
'created_date',
'updated_date',
]
read_only_fields = ['user']
它是相关模型:
class Peyment(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id',
related_name='product_peyment')
status = models.CharField(max_length=30, null=True)
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
transfer_id = models.CharField(max_length=100, null=True, blank=True)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
答案 0 :(得分:1)
SerializerMethodField
是read_only字段。您需要将其替换为PrimaryKeyRelatedField
以发布product_id数据:
class PeymentSerializer(ModelSerializer):
product = serializers.PrimaryKeyRelatedField()
user = serializers.SerializerMethodField()
def get_user(self, obj):
return obj.id
class Meta:
model = Peyment
fields = [
'product',
'status',
'user',
'transfer_id',
'created_date',
'updated_date',
]
read_only_fields = ['user']
由于PrimaryKeyRelatedField
是关系的默认字段,因此您可以删除显式定义。对于用户字段也是如此:
class PeymentSerializer(ModelSerializer):
class Meta:
model = Peyment
fields = [
'product',
'status',
'user',
'transfer_id',
'created_date',
'updated_date',
]
read_only_fields = ['user']