Arslan Yersain
Arslan Yersain

Reputation: 37

How to pass data to serializers in django

I want to pass user_id from view to serializer I have model Answer

class Answer(models.Model) :
    
    text = models.CharField(max_length=500)
    question_id = models.CharField(max_length=25)
    user_id = models.CharField(max_length=25, default=1)

This is my Serializer

class CreateAnswer(generics.CreateAPIView) :

    def get_serializer_context(self):
        context = super().get_serializer_context()
        context["id"] = self.request.user.id
        return context

    serializer_class = AnswerQuestionSerializer
    queryset = Answer.objects.all()

What I need to write in my view to take user_id and create model with this user_id ?

Upvotes: 2

Views: 2132

Answers (3)

Maha Irfan
Maha Irfan

Reputation: 21

There are multiple ways to do this task. One of them is to override create in your serializer. Following is the code snippet:

class BlogSerializer(serializers.Serializer):

  def create(self, validated_data):
    user = self.context['request'].user
    blog = Blog.objects.create(
       user=user, 
       **validated_data
    )
    return blog

Explanation: A context is passed to the serializer which contains the request by default. So you can access the user easily with self.context['request'].user

Upvotes: 0

Arslan Yersain
Arslan Yersain

Reputation: 37

You can use serializers.Hiddenfield to get current user in serializer class

https://www.django-rest-framework.org/api-guide/fields/#hiddenfield

Upvotes: 0

Ajay Lingayat
Ajay Lingayat

Reputation: 1673

You can override the perform_create method & pass the user_id field to save method of the serializer.

class CreateAnswerView(generics.CreateAPIView) :
    serializer_class = AnswerQuestionSerializer

    def perform_create(self, serializer):
        serializer.save(user_id=self.request.user.id)

Upvotes: 4

Related Questions