Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-viewsdjango-serializer

How to perform multiple insertion using django rest viewsets?


I'm working on this api where a user can select multiple languages and can mark the proficiency in each language. The model is as follows.

class UserLanguage(models.Model):
  user = models.ForeignKey(User, on_delete=models.CASCADE)
  language = models.ForeignKey(Language, on_delete=models.CASCADE)
  proficiency = models.DecimalField(max_digits=4, decimal_places=2)

  class Meta:
      db_table = "user_language"

Serializer looks like:

class UserLanguageSerializer(serializers.ModelSerializer):

  class Meta:
      model = UserLanguage
      fields = '__all__'

I have done the views as follows

class UserLanguageViewSet(viewsets.ModelViewSet):
  queryset = UserLanguage.objects.all()
  serializer_class = UserLanguageSerializer

The code works fine for a request like

{
    "proficiency": "04.00",
    "user": 1,
    "language": 1
}

I want the api to accept a list like this:

[
{
    "proficiency": "05.00",
    "user": 1,
    "language": 1
},
{
    "proficiency": "04.00",
    "user": 1,
    "language": 1
}]

For each item in the list I want to create a new row in 'user_language' table.

Am I doing it the right way? If not show me the right way.

How should I modify my models, serializer or view to attain this?

I don't know if the above request is in the right format. If not please let me know.

Thank you.


Solution

  • You want to override the create method so the serializer accepts many=True.

    class UserLanguageViewSet(viewsets.ModelViewSet):
        queryset = UserLanguage.objects.all()
        serializer_class = UserLanguageSerializer
    
        def create(self, request):
            serializer = UserLanguageSerializer(data=request.data, many=True)
            if serializer.is_valid:
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)