Django REST Framework - Serializer data failure with request data
I wanted to have a serializer that will read as fields object in linked models, but store as pk value for linked object. Something like a nested model with depth=1
, but with more flexibility for a nested model. Essentialy I need the following query structure
GET child / {id}
{
"id": 1,
"name": "child",
"parent": {
"id": 1,
"name": "parent"
}
}
POST child / {id}
{
"id": 1,
"name": "child",
"parent": 1
}
So, I wrote the following serializers:
# 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')
This works almost as expected, but the child serializer does not work when passing the request. To illustrate the problem:
# 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'
As a workaround, I forced to ChildSerializer
convert the QueryDicts to normal dictionaries, but I would still like to know why this is above and if there is a better option for this type of API structure.
source to share
No one has answered this question yet
Check out similar questions: