'Where to put the logic for filling out fields of an object during post request?
I am currently working on a post request for an image labelling game. Basically a user should see a picture that is shown to them through a get request and the user can label this picture (the resource).
This id my serializer:
class TaggingSerializer(serializers.ModelSerializer):
tag = TagSerializer(required=False, write_only=False)
resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
required=True,
source='resource',
write_only=False)
gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
required=False,
source='gameround',
write_only=False)
user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
required=False,
source='user',
write_only=False)
class Meta:
model = Tagging
fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag', 'created', 'score', 'origin')
depth = 1
def create(self, validated_data):
"""Create and return a new tagging"""
tag_data = validated_data.pop('tag', None)
if tag_data:
tag = Tag.objects.get_or_create(**tag_data)[0]
validated_data['tag'] = tag
tagging = Tagging(
user=validated_data.get("user"),
gameround=validated_data.get("gameround"),
resource=validated_data.get("resource"),
tag=validated_data.get("tag"),
created=datetime.now(),
score=validated_data.get("score"),
origin=validated_data.get("origin")
)
tagging.save()
return tagging
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['tag'] = TagSerializer(instance.tag).data
return rep
and this is my post request:
def post(self, request, *args, **kwargs):
tag_serializer = TagSerializer(data=request.data)
tagging_serializer = TaggingSerializer(data=request.data)
if tagging_serializer.is_valid(raise_exception=True):
tagging_serializer.save(tagging=request.data)
return Response({"status": "success", "data": tagging_serializer.data}, status=status.HTTP_201_CREATED)
else:
return Response({"status": "error", "data": tag_serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
At the moment, testing my post request works with such an object:
{
"user_id": 1,
"gameround_id": 2015594866,
"resource_id": 2975,
"tag": {
"name": "NewTagToTestTheoryThatblabla",
"language": "en"
},
"score": 0,
"origin": ""
}
I think for my use case I need to be able to send such a json object:
{
"name": "NewTagToTestTheoryThatblabla",
"language": "en"
}
where the other fields are filled out with data that was previously sent through the get request. Correct me if I am wrong here.
My question is, how can I achieve this?
*I have tried writing the logic in the post method and it doesn't work so I suspect I have to write it in the Serializer - since this is what I am doing for the 'created' field for example.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
