Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST serialize single model instance

I'm trying to serialize a model instance of type Shift but I'm getting an error.

'Shift' object has no attribute 'get'

shift = models.Shift.objects.get(pk=8)
ser = serializers.ShiftSerializer(many=False, data=shift)
ser.is_valid()

ShiftSerializer is a ModelSerializer. This works if I get the shift using filter and all and many=True.

Solution:

shift = models.Shift.objects.get(pk=8)
ser = serializers.ShiftSerializer(shift)
like image 495
user3043893 Avatar asked Sep 01 '15 10:09

user3043893


People also ask

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.


1 Answers

The data parameter is for deserializing, not serializing. You should just pass the model instance as a positional arg.

obj = serializers.ShiftSerializer(shift)

Note there's no need to specify many=False, that's the default. Also, it doesn't make sense to call is_valid() on the serializer you've constructed from a model instance; again, that's for deserialization.

like image 180
Daniel Roseman Avatar answered Oct 13 '22 02:10

Daniel Roseman