codelearner
codelearner

Reputation: 87

How do I deserialize list of multiple objects in django rest framework?

I am developing a rest API that gets requests composed of multiple objects and saves them to the database. Then, another array of objects is returned as the response. All objects are of only one model.

class Ratings(models.Model):
    id = models.AutoField(primary_key = True)
    userId = models.IntegerField()
    movieId = models.IntegerField()
    rating = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)])
    timestamp = models.DateTimeField(auto_now = True)

class RatingsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ratings
        fields = ('userId','movieId','rating')

class RecommendationGenerator(generics.ListCreateAPIView):
    queryset = Ratings.objects.all()
    serializer_class= RatingsSerializer
    def post(self, request, format='json'):
        serializer= RatingsSerializer(data = request.data, many = True)
        if serializer.is_valid():
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_403_FORBIDDEN)

When I test it in Postman with the JSON:

[
    {
        "userId": 13,
        "movieId": 1765,
        "rating": 5
    },
    {
        "userId": 13,
        "movieId": 1733,
        "rating": 3
    },
    {
        "userId": 13,
        "movieId": 1713,
        "rating": 2
    },
    {
        "userId": 13,
        "movieId": 963,
        "rating": 2
    }
]

The result is []. But for

{
    "userId": 13,
    "movieId": 1765,
    "rating": 5
}

The result is

{
    "userId": 13,
    "movieId": 1765,
    "rating": 5
}

How do I deserialize this data? What am I doing wrong here?

Upvotes: 4

Views: 3329

Answers (2)

codelearner
codelearner

Reputation: 87

The code works fine. The problem was that the request sent was in the form of Text instead of 'application/json'. Thanks for the help anyways.

Upvotes: 2

Shihabudheen K M
Shihabudheen K M

Reputation: 1397

views should be like

class RecommendationGenerator(generics.ListCreateAPIView):
    queryset = Ratings.objects.all()
    serializer_class= RatingsSerializer

    def post(self, request, format='json'):
        serializer= RatingsSerializer(data = request.data, many = True)
        if serializer.is_valid():
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_403_FORBIDDEN)

Try This

Upvotes: 2

Related Questions