简体   繁体   中英

Object of type CharField is not JSON serializable

I'm learning Django by trying to build what comes to the mind. Now I'm trying to build Django rest API that returns item or all items from a postgres data table.

models.py

class AdModel(models.Model):
    id = models.IntegerField
    name = models.CharField(max_length=50),
    address = models.CharField(max_length=50),
    web = models.CharField(max_length=50),

    class Meta:
        db_table = 'mock_location_data'

serializers.py

class AdSerializer(serializers.ModelSerializer):
class Meta:
    model = AdModel
    fields = ['id', 'name', 'address', 'web']

views.py

class AdAPIView(APIView):

    def get(self, request):
        queryset = AdModel.objects.all()
        serializer_class = AdSerializer(queryset, many=True)
        return Response(serializer_class.data)

On GET request I'm getting Internal server error 500 with "Object of type CharField is not JSON serializable"

in views.py if replace fields = ['id', 'name', 'address', 'web'] with

fields = '__all__'

I'm getting all the id fields

[  {    "id": 1  },  {    "id": 2  },  {    "id": 3  },.....]

but no other data

I'm using Django 3.1.5 and DRF 3.12.2

You missed a pair of parentheses in your AdModel class's id field and also don't need "," after each field:

class AdModel(models.Model):
    id = models.IntegerField()
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=50)
    web = models.CharField(max_length=50)

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