DRF serialize through related models data

345 Views Asked by At

I've got a problem with DRF serialization. My main goal is to create an instance which has a related field but instead of providing the related models id i want to use it's other unique field. At the same time when I will serialize my model to present it (not create) i would like to get the default related fields value. Here's an example

class Comment(models.Model):

    description = models.TextField()
    creator = models.ForeignKey(User, ...)


x = Creator.objects.get(pk=1)
print(x.unique_field)
> 'some data'
client.post('comment-detail', data={
                                     'description': 'some description',
                                     'creator_unique_field': 'some data'
                                    })
# this should create a comment while using some unique creators field
# which is not pk or id

print(client.get('comment-detail', data={'pk':1}))
{
  'description' 'some description',
  'creator': 1,
}
        

I don't know If i should change models Serializer of ViewSet's create() and retrieve(). Im starting with DRF and can't get my head around it

1

There are 1 best solutions below

0
On BEST ANSWER

Overriding the Serializer create method is a good place for this. one can query for the unique_field user there.

class CommentView(viewsets.ModelViewSet):
    def perform_create(self, serializer):
        serializer.save(creator=self.request.user)

class CommentSerializer(serializers.Serializer):

    creator_unique_field = serializer.SomeField()        

    def create(self, validated_data):
        creator = Creator.objects.get(unique_field=validated_data['creator_unique_field'])
        comment, created = Comment.objects.get_or_create(creator=creator, **validated_data)

        return comment

    class Meta:
        model = Comment
        fields = '__all__'