简体   繁体   中英

Django Serializer only serializing objects with many=True

I am trying to make a serializer

class StoreSerializer(serializers.ModelSerializer):
    class Meta:
        model = Store
        fields = '__all__'

and in the viewset,

def list(self, request, *args, **kwargs):
    obj = Store.objects.first()
    ser = StoreSerializer(data=obj)
    if ser.is_valid():
        pass
    print(ser.data)
    return Response(ser.data)

this method is returning just an empty dict {} as the response. When defining the serializer as

ser = StoreSerializer(data=[obj], many=True)

the object is getting serialized. What am I doing wrong here?

When you are passing a models data to a ModelSerializer you don't need to call the function

serializer.is_valid()

So you can just pass the data without the data key as

ser = StoreSerializer(obj)
print(ser.data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM