我想要一个序列化程序,它将作为相关模型上的字段对象读取,但保存为相关对象的pk值。类似于depth=1
的嵌套模型,但在嵌套模型上具有更大的灵活性。 Essentialy我想要以下查询结构
获取孩子/ {id}
{
"id": 1,
"name": "child",
"parent": {
"id": 1,
"name": "parent"
}
}
POST child / {id}
{
"id": 1,
"name": "child",
"parent": 1
}
所以我编写了以下序列化程序:
# models.py
class Parent(models.Model):
name = models.CharField(max_length=255)
class Child(models.Model):
name = models.CharField(max_length=255)
parent = models.ForeignKey(Parent)
# serializers.py
class ParentSerializer(serializers.ModelSerializer):
"""Write as pk, read as object"""
class Meta:
model = models.Parent
fields = ('id', 'name')
def to_internal_value(self, data):
return self.Meta.model.objects.get(pk=data)
class ChildSerializer(serializers.ModelSerializer):
parent = ParentSerializer()
class Meta:
model = models.Child
fields = ('id', 'name', 'parent')
这几乎按预期工作,但子序列化程序在通过querydict时不起作用。为了说明问题:
# This works great! everything as expected
parent = Parent.objects.create(name='parent')
data = {'name': 'child', 'parent': parent.pk}
serializer = ChildSerializer(None, data=data)
serializer.is_valid()
serializer.save()
# This borks
data = QueryDict('name={0}&parent={1}'.format('child', parent.pk))
serializer = ChildSerializer(None, data=data)
serializer.is_valid()
serializer.save()
TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict'
作为一种解决方法,我强制ChildSerializer
将QueryDicts转换为普通字典,但我仍然想知道为什么上述操作失败以及是否有更好的选择这种API结构