Bhupesh Parakh
Bhupesh Parakh

Reputation: 1163

Why my django server throws an error of invalid datatype?

Whenever i called my booking function with a post method in that it throws me an error of 'Invalid Data Type it expected dict but its an int'. So when i debug that i found a problem in my serializers so Please help me to resolve the error

model.py

class Booking(models.Model):
    details = models.ForeignKey(PersonalDetails, on_delete=models.CASCADE)
    quantity = models.IntegerField(null=False)
    total_amount = models.IntegerField()
    show = models.ForeignKey(ShowTime, on_delete=models.CASCADE)

    def __str__(self) -> str:
        return self.total_amount

views.py


class BookingTicketsQuery(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, format=None):
        booking_id = request.query_params.get('booking_no', None)
        if booking_id is not None:
            queryset = Booking.objects.get(id=booking_id)
        else:
            return Response("invalid", status=status.HTTP_409_CONFLICT)
        seriliazer = BookingSerializer(queryset)
        return Response(seriliazer.data)

    def post(self, request, format=None):
        recieve_data = JSONParser().parse(request)
        showtime = ShowTime.objects.get(id=recieve_data['show'])
        print(showtime)

        if recieve_data['quantity'] > (showtime.total_seats - showtime.booked_seats):
            return Response("Error: No seats available", status=status.HTTP_409_CONFLICT)

        recieve_data['total_amount'] = showtime.total_price * \
            recieve_data['quantity']
        showtime.booked_seats += recieve_data['quantity']
        showtime.save()

        serializer = BookingSerializer(data=recieve_data)
        if serializer.is_valid():
            booking_obj = serializer.save()
            return Response(booking_obj.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializers.py


class ShowMovieSerializer(serializers.ModelSerializer):
    cinema = CinemaSerializer()
    movie = MovieSerializer()

    class Meta:
        model = ShowTime
        fields = ('id', 'show_start_time', 'show_end_time',
                  'total_seats', 'booked_seats', 'cinema', 'movie')

class BookingSerializer(serializers.ModelSerializer):
    show = ShowMovieSerializer()
    details = PersonalDetailsSerializer()


    class Meta:
        model = Booking
        fields = ('id', 'total_amount', 'quantity', 'details', 'show')

traceback

Bad Request: /api/v1/bookings/ [19/Jul/2021 12:07:20] "POST /api/v1/bookings/ HTTP/1.1" 400 168

{
    "details": {
        "non_field_errors": [
            "Invalid data. Expected a dictionary, but got int."
        ]
    },
    "show": {
        "non_field_errors": [
            "Invalid data. Expected a dictionary, but got int."
        ]
    }
}

my post data: { "details": 1, "quantity":1, "show":1 }

Upvotes: 0

Views: 326

Answers (1)

Klim Bim
Klim Bim

Reputation: 646

You added a ShowMovieSerializer() and PersonalDetailsSerializer(). Therefore drf expects data that represents both models (nested data). What you have to do instead of posting { "details": 1, "quantity":1, "show":1 }-data you have to adjusted your data that represents your model. You are posting data with a pk of your Movie and Show.

For instance:

{
"id":....,
"total_amount": ....,
....
"movie": {
          "title": ....,  # fields are only for explanation
          "length": ....
         },
"show": {
         "title": ....,
         "actor": ....
        }
}

If you only want to establish a relationship between you ShowTime and Booking you have to remove your serializers.

dealing with nested data

Upvotes: 1

Related Questions