Как передать контекст из одного сериализатора в другой в DRF [2024]?Python

Программы на Python
Anonymous
Как передать контекст из одного сериализатора в другой в DRF [2024]?

Сообщение Anonymous »


I have seen many duplicate threads on this, most notably this context in nested serializers django rest framework, but none have worked for me. I have tried most solutions I see in every thread most notably CustomSerializers, using parents init(), and using parents to_representation(), but the context never passes from parent to child. Apparently it is supposed to pass automatically as of the newer django versions but it doesnt for me. (Django 5.0.2)

In my example I serialize a post which's comments are serialized by calling the comment serializer. For every comment being serialized, I want to check if the user has voted on it yet by creating a field user_vote. When I print the request from the parent it prints normally, however from the child it request is empty.

Serializers.py
class CommentSerializer(ModelSerializer): child_comment = serializers.SerializerMethodField() user_vote = serializers.SerializerMethodField() class Meta: model = Comment fields = '__all__' def get_user_vote(self, obj): # Get the current user from the request print(self.context, file=sys.stderr) user = self.context['request'].user # Check if a vote exists for the current user and comment try: vote = Vote.objects.get(user=user, comment=obj) return vote.value except Vote.DoesNotExist: return 0 class PostSerializerSingle(ModelSerializer): images = SheetMusicImageSerializer(many=True) comments = CommentSerializer(many=True) class Meta: model = Post fields = '__all__'

Источник: https://stackoverflow.com/questions/781 ... n-drf-2024

Вернуться в «Python»