使用PrimaryKeyRelatedField保存django-rest

时间:2016-12-01 03:06:20

标签: django serialization django-rest-framework

我正在构建一个允许发布到django后端的端点。 Deal Model有ManyToMany Relation top book runner,我的序列化器默认下面有PrimaryKeyRelatedField:

Models.py

class Deal(models.Model):
    book_runner = models.ManyToManyField(BookRunner, blank=True, null=True, related_name="deal_book_runner")

Serializers.py

class DealSerializer(serializers.ModelSerializer):
    book_runner = PrimaryKeyRelatedField(allow_null=True, many=True, queryset=BookRunner.objects.all(), required=False)
    equity = Equity.objects.create(**equity_data)

def create(self, validated_data):
    deal = Deal.objects.create(**validated_data)
    return deal

Views.py

class DealAdminViewSet(viewsets.ModelViewSet):
    queryset = Deal.objects.all()
    serializer_class = CreateDealSerializer

    def create(self, request, format=None):
        book_runner = request.data.get('book_runner', None) #array

在验证之前打印数据(validated_data)程序中断:

{'book_runner': u'2'}

现在当我与主键= 2的书籍发布者发布交易时,我收到错误:

File "/usr/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <property object at 0x7f1559578158> is not JSON serializable

我想在将来使用数组和主键数。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

这是关于您发送到rest框架的JSON的错误。它没有成功地将其反序列化。 检查JSON格式是否有效。