gpt4 book ai didi

python - 作为 JSON 字符串数组而不是键值数组返回

转载 作者:太空宇宙 更新时间:2023-11-04 00:13:05 25 4
gpt4 key购买 nike

我正在使用 Django 编写一个 Web 服务,并试图创建一个 API 来返回我在 MySQL 数据库中的一个表中的所有不同类别。表架构如下:

+---------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| news_id | int(11) | YES | MUL | NULL | |
| news_category | varchar(50) | YES | | NULL | |
| publish_date | varchar(50) | YES | | NULL | |
| news_link | varchar(255) | NO | | NULL | |
+---------------+--------------+------+-----+---------+----------------+

这里的news_category 字段不是唯一的。我希望 API 以以下 JSON 格式列出所有不同的类别:

{
"count": 22,
"next": null,
"previous": null,
"results": ["apple", "google", "microsoft", "apps", "photography", "virtual-reality", "business"]
}

以下是我的models.py:

from django.db import models
...
class NewsInfo(models.Model):
news = models.ForeignKey(NewsContent, models.DO_NOTHING, blank=True, null=True)
news_category = models.CharField(max_length=50, blank=True, null=True)
publish_date = models.CharField(max_length=50, blank=True, null=True)
news_link = models.CharField(max_length=255)

def __str__(self):
return self.news.news_title

class Meta:
managed = False
db_table = 'news_info'

serializers.py:

from .models import NewsInfo
from rest_framework import serializers
...
class NewsInfoSerializer(serializers.ModelSerializer):
class Meta:
fields = ['news_category', 'news_link', 'news']
model = NewsInfo

class NewsCategorySerializer(serializers.ModelSerializer):
class Meta:
fields = ['news_category']
model = NewsInfo

views.py:

from rest_framework import viewsets
from .models import NewsInfo
from .serializers import NewsCategorySerializer
...
class CategoryViewSet(viewsets.ModelViewSet):
queryset = NewsInfo.objects.values('news_category').distinct()
serializer_class = NewsCategorySerializer

我在这里得到响应,但是像这样的键值对:

{
"count": 22,
"next": null,
"previous": null,
"results": [{
"news_category": "apple"
}, {
"news_category": "google"
}, {
"news_category": "microsoft"
}, {
"news_category": "apps"
}, {
"news_category": "photography"
}, {
"news_category": "virtual-reality"
}, {
"news_category": "business"
}]
}

无论我尝试什么,我都无法得到我想要的结果。请帮忙。

最佳答案

重写 to_representation() 方法作为 NewsCategorySerializer 序列化器,

class NewsCategorySerializer(serializers.ModelSerializer):
class Meta:
fields = ['news_category']
model = NewsInfo

<b>def to_representation(self, instance):
return super().to_representation(instance)['news_category']</b>

关于python - 作为 JSON 字符串数组而不是键值数组返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51805867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com