New to the Django REST Framework. Serialization continues. I do not understand how to deserialize a related object, given only its primary key from the database. Here is what I mean:
class ThingA(models.model):
name = models.CharField(max_length=25)
role = models.CharField(max_length=25, null=True, blank=True)
class ThingB(models.model):
name = models.CharField(max_length=25)
athing = models.ForeignKey(ThingA)
Suppose I have a POST /thingbREST call to create a new one ThingB, and the payload contains a name for the new one ThingBand idfor the associated one ThingA(which already exists in the database):
{
"name": "Name for new ThingB",
"athing" : 5
}
How do I write a Serializer DRF that can also deserialize this payload to end up ThingBwith whose attribute athingis an object ThingAwith id = 5? I tried using DRF ModelSerializers, so I got this far:
class ThingASerializer(serializers.ModelSerializer):
class Meta:
model = ThingA
fields = ('id', 'name', 'role')
class ThingBSerializer(serializers.ModelSerializer):
a_thingie = ThingASerializer(source='athing')
class Meta:
model = ThingB
fields = ('id', 'name', 'a_thingie')
, , JSON . , ? , :
b = ThingBSerializer(data=request.DATA)
, , restore_object serializer, , restore_object . - ? !