gpt4 book ai didi

python - 将 url 添加到 Serializers.Serializer 上的 API 响应

转载 作者:行者123 更新时间:2023-12-01 07:24:28 26 4
gpt4 key购买 nike

我有一个包含以下文件的 django 应用程序

models.py

from datetime import datetime

class Comment(object):
def __init__(self, email, content, created=None):
self.email = email
self.content = content
self.created = created or datetime.now()

序列化器.py

from rest_framework import serializers

class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
url = serializers.CharField(source='get_absolute_url', read_only=True)

在views.py中,我现在定义一个ViewSet来返回序列化结果。在此类中,我定义了一个评论列表

views.py

from rest_framework import viewsets
from .serializers import *
from .models import Comment
from rest_framework.response import Response


class CommentViewSet(viewsets.ViewSet):
lc = [Comment(email='jan@auto.com', content='hallo mike'),
Comment(email='jan@auto.com', content='hallo jan'),
Comment(email='jan@auto.com', content='hallo niklas')]

def list(self, request):
serializer = CommentSerializer(self.lc, many=True)
return Response(serializer.data)

def retrieve(self, request, pk=None):
user = self.lc[int(pk)]
serializer = CommentSerializer(user)
return Response(serializer.data)

当我现在调用 api (http://127.0.0.1:8000/comments/?format=json) 时,我得到以下结果

[
{
"email": "jan@auto.com",
"content": "hallo mike",
"created": "2019-08-16T16:53:56.371890Z"
},
{
"email": "jan@auto.com",
"content": "hallo jan",
"created": "2019-08-16T16:53:56.371890Z"
},
{
"email": "jan@auto.com",
"content": "hallo niklas",
"created": "2019-08-16T16:53:56.371890Z"
}
]

在此响应中,我希望看到每个数据集的 URL。错误可能是 url = serializers.CharField(source='get_absolute_url', read_only=True) 的来源在 Comment 类中未定义。但是我不知道如何实现这一目标。如有任何帮助,我们将不胜感激。

最佳答案

您需要定义一个 get_absolute_url method [Django-doc]在您的模型上,例如:

# app/models.py

from django.db import models
from django.urls import reverse

class Comment(models.Model):
email = models.EmailField()
content = models.CharField(max_length=128)
created = models.DateTimeField(auto_now_add=True)

def <b>get_absolute_url</b>(self):
return <b>reverse(</b><i>'name-of-view'</i>, kwargs={'pk': self.pk}<b>)</b>

这里'name-of-view'是您定义的 View 的名称,例如在urls.py中,并且kwargs=... 被赋予一个映射相应 URL 路径参数值的字典。

关于python - 将 url 添加到 Serializers.Serializer 上的 API 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57526886/

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