从ListAPIView Django 3.0 Rest框架返回自定义JSON响应

2024-06-02 06:17:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经使用DRF创建了一个API,它能够根据指定的URL模式列出和查看特定记录。例如:

关于请求:

curl -v http://127.0.0.1:8000/get_details/120001/

我能得到一个答复:

[
    {
        "subject": "Data Structures",
        "course": "CSE"
    },
    {
        "subject": "Thermodynamics",
        "course": "Chemistry"
    },
    {
        "subject": "Organic Chemistry",
        "course": "Chemistry"
    },
    {
        "subject": "Optics",
        "course": "Physics"
    }
]

其中“120001”是搜索数据库所依据的用户id。 但我希望得到以下格式的响应:

{'Chemistry': ['Thermodynamics', 'Organic Chemistry'], 'CSE': ['Data Structures'], 'Physics': ['Optics']}

(就内容而言,我没有考虑缩进和其他因素)

虽然我能够为如何创建和填充此词典的逻辑编写代码,但我无法确定如何将其作为响应返回以及从何处返回。

我使用泛型.ListAPIView作为视图类

这是我的模型(models.py):

class Subject(models.Model):
    user_id = models.CharField(null = False, max_length=10)
    subject = models.CharField(max_length=50)
    course = models.CharField(max_length=50)

    def __str__(self):
        return self.subject

序列化程序(serializers.py):

class SubjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Subject
        fields = ['subject', 'course']

和,views.py(对于默认格式的第一个输出):

class SubjectView(generics.ListAPIView):
    serializer_class = SubjectSerializer

    def get_queryset(self):
        username = self.kwargs['user_id']
        return Subject.objects.filter(user_id = username).only('subject','course')

我已经编写了一个逻辑,通过使用Subject.objects.values(..)提取值,然后循环结果来创建我的字典,创建字典以作为响应发送(如我所需的输出中所述),但我不知道在何处(即哪个函数)写入并返回

generics.ListAPIView类提供的函数是否允许我执行此操作?如果没有,我还可以尝试其他方法吗?

我是Django的初学者,任何帮助都将不胜感激。此外,如果有人能向我推荐一个实用指南/教程/播放列表,我可以通过代码示例学习DRF,从而加快我的学习过程,这将非常有帮助

谢谢大家!


Tags: pyselfidmodelslengthmaxdrfclass
1条回答
网友
1楼 · 发布于 2024-06-02 06:17:37

您需要重写Serializerto_representation方法

docs

There are some cases where you need to provide extra context to the serializer in addition to the object being serialized.

class SubjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Subject
        fields = ['subject', 'course']

    def to_representation(self, instance):
        data = super(SubjectSerializer, self).to_representation(instance)
        # manipulate data here 
        return data

相关问题 更多 >