简体   繁体   English

CharField 类型的 Object 不是 JSON 可序列化的

[英]Object of type CharField is not JSON serializable

I'm learning Django by trying to build what comes to the mind.我正在通过尝试构建想到的东西来学习 Django。 Now I'm trying to build Django rest API that returns item or all items from a postgres data table.现在我正在尝试构建 Django rest API 从 postgres 数据表中返回项目或所有项目。

models.py模型.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序列化程序.py

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

views.py视图.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"在 GET 请求中,我收到内部服务器错误 500,其中“CharField 类型的对象不是 JSON 可序列化的”

in views.py if replace fields = ['id', 'name', 'address', 'web'] with在 views.py 中,如果将 fields = ['id', 'name', 'address', 'web'] 替换为

fields = '__all__'

I'm getting all the id fields我正在获取所有 id 字段

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

but no other data但没有其他数据

I'm using Django 3.1.5 and DRF 3.12.2我正在使用 Django 3.1.5 和 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:您在 AdModel 类的 id 字段中遗漏了一对括号,并且在每个字段之后也不需要“,”:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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