[Answered ]-Pass user data to serializer in nested serializers when creating object in django rest framework

1👍

If you don’t want to create a User when creating an Announcement, omit the author field from your AnnouncementSerializer, then pass the current user when saving serializer object:

serializer.py

class AnnouncementSerializer(serializers.ModelSerializer):
    parameters = ParameterSerializer(many=True, required=False)
    photo = PhotoSerializer(many=True, required=False)

    class Meta:
        model = Announcement
        fields = ['id', 'name', 'parameters', 'photo']

views.py

class AnnouncementCreate(CreateAPIView):
    permission_classes = [IsAuthenticated]
    queryset = models.Announcement.objects.all()
    serializer_class = AnnouncementSerializer

    def perform_create(self, serializer):
        serializer.save(author=self.request.user)
👤Amin

Leave a comment