TypeError: Object of type 'TopicSerializer' is not JSON serializable Django

TypeError: Object of type 'TopicSerializer' is not JSON serializable Django

大家好 我在收到 API 回复时遇到了这个问题。我正在使用 django==2.1.7。下面我添加了我的代码片段

models.py

模型包含主题名称(en,bn)、标签列表(string)和Bucket_id或topic_id


class Topics(models.Model):
    id = models.AutoField(primary_key=True)
    name_en = models.CharField(max_length=70, blank=False, default='')
    name_bn = models.CharField(max_length=70, blank=False, default='')
    tags = models.TextField(blank=False, default='')
    bucket_id = models.IntegerField()


    def set_tags(self, x):
        self.tags = json.dumps(x)

    def get_tags(self):
        return json.loads(self.tags)


    class Meta:
        managed = True
        db_table = 'follow_topics'

serialize.py

TopicSeializer 用于JSON序列化模型

from rest_framework import serializers 
from .models import Topics
 
 
class TopicSerializer(serializers.ModelSerializer):
    class Meta:
        model = Topics
        fields = ['name_en','name_bn','tags', 'bucket_id']

views.py

get_topic 函数为我提供了模型中的主题列表


@api_view(('GET',))
def get_topics(requests):
    topic_id = requests.GET.get('topic_id', None)
    post_data = Topics.objects.filter(bucket_id=topic_id)
    serialize_data = TopicSerializer(post_data, many=True)

    return Response({"status": "success", "data": serialize_data})

我遇到了可序列化错误。这个错误看起来让我很沮丧。请帮我分享一些有用的资源或方法来修复这个错误

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/feed/v1/get_topics?topic_id=2

Django Version: 2.1.7
Python Version: 3.6.8
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'debug_toolbar',
 'rest_framework',
 'feedv1']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.BrokenLinkEmailsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware']



Traceback:

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  156.                 response = self.process_exception_by_middleware(e, request)

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  154.                 response = response.render()

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/template/response.py" in render
  106.             self.content = self.rendered_content

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/response.py" in rendered_content
  72.         ret = renderer.render(self.data, accepted_media_type, context)

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in render
  733.         context = self.get_context(data, accepted_media_type, renderer_context)

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in get_context
  688.             'content': self.get_content(renderer, data, accepted_media_type, renderer_context),

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in get_content
  424.         content = renderer.render(data, accepted_media_type, renderer_context)

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in render
  107.             allow_nan=not self.strict, separators=separators

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/utils/json.py" in dumps
  28.     return json.dumps(*args, **kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py" in dumps
  238.         **kw).encode(obj)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in encode
  201.             chunks = list(chunks)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode
  430.             yield from _iterencode_dict(o, _current_indent_level)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode_dict
  404.                 yield from chunks

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode
  437.             o = _default(o)

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/utils/encoders.py" in default
  68.         return super(JSONEncoder, self).default(obj)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in default
  180.                         o.__class__.__name__)

Exception Type: TypeError at /feed/v1/get_topics
Exception Value: Object of type 'TopicSerializer' is not JSON serializable

您需要访问序列化器.data 属性

return Response({"status": "success", "data": <b>serialize_data.data</b>})