Home > OS >  How to pass data to serializers in django
How to pass data to serializers in django

Time:10-22

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 ?

CodePudding user response:

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)
  • Related