I currently have a model serializer with a foreign key field. I would like the related model to a serialized object rather than just an ID. I know this is possible by creating a serializer for the related model and doing
related_field = RelatedFieldSerializer()
However, how do I handle the case when creating/updating occurs for the main object? E.g. I want to create an instance of the main object but the related field will get sent as an object (not a pk) and won't refer to the existing foreign key, it will try to create a new object instead.
Hope this makes sense
If you don't want to create the existing object, you can do something like this where you leverage
PrimaryKeyRelatedField
as documented here.models.py
Then your
serializers.py
would look like:Then posts can be made against the
pk
value of existingModel1
values in the database. Note, you could use other values than thepk
value if needed. See this post.You have to override the
create
andupdate
methods of your serializer. Thecreate
method could look like this:For more information see the documentation about Writable nested representations