I have this code in Django using the REST framework. Here are my models, serializer, views:
model:
class Car(AbstractTimeTrackable, models.Model):
production_type = models.ForeignKey(
'cars.CarProductionType',
on_delete=models.PROTECT,
related_name='cars',
verbose_name=_('production_type')
)
warehouse = models.ForeignKey(
'warehouses.Warehouse',
on_delete=models.SET_NULL,
verbose_name=_('warehouse'),
related_name='cars',
blank=True,
null=True,
)
class Meta:
verbose_name = _('Auto')
verbose_name_plural = _('Auto')
def __str__(self):
return str(self.id)
class Reservation(AbstractTimeTrackable, models.Model):
is_active = models.BooleanField(
default=False,
verbose_name=_('is_active')
)
cars = models.ManyToManyField(
'cars.Car',
verbose_name=_('ID cars')
)
class Meta:
verbose_name = _('Reservation')
verbose_name_plural = _('Reservation')
def __str__(self):
return str(self.id)
serializer:
class ReservationSerializer(serializers.ModelSerializer):
days_count = serializers.IntegerField(required=True)
cars = serializers.PrimaryKeyRelatedField(queryset=Car.objects.all(), many=True)
class Meta:
model = Reservation
fields = [
'id',
'is_active',
'cars'
]
extra_kwargs = {
'id': {'read_only': True}
}
def create(self, validated_data):
cars = validated_data.pop('cars')
instance = super().create(validated_data)
if cars:
instance.cars.add(*cars)
return instance
view:
class ReservationViewSet(CreateModelMixin, GenericViewSet):
serializer_class = ReservationSerializer
queryset = Reservation.objects.all()
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(status=status.HTTP_201_CREATED, data=serializer.validated_data)
I am getting this error message:
TypeError at /api/v1/reservations/ Object of type Car is not JSON serializable
I need only PrimaryKey of Cars; that's why I use PrimaryKeyRelatedField.
How can I resolve this error?
CodePudding user response:
You need to return serializer.data
instead of serializer.validated_data
.
Have a look at the updated code for ReservationViewSet
:
class ReservationViewSet(CreateModelMixin, GenericViewSet):
serializer_class = ReservationSerializer
queryset = Reservation.objects.all()
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(status=status.HTTP_201_CREATED, data=serializer.data)
the data
property is meant to translate the model instance into the Python native dictionary type. Python Dictionary can be serialized as a JSON Response.