Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将数据添加到Django REST Framework返回的列表中';s模型视图集_Django_Django Rest Framework - Fatal编程技术网

将数据添加到Django REST Framework返回的列表中';s模型视图集

将数据添加到Django REST Framework返回的列表中';s模型视图集,django,django-rest-framework,Django,Django Rest Framework,是否有方法将自定义数据添加到使用Django REST Framework的ModelViewSet的视图的列表API调用返回的结果数据中 “我的模型视图集”视图附着到项目模型 除了listapi调用返回的项目列表之外,我还想查询一个单独的seed模型,并返回每个项目的查看次数 我还想在返回的数据中添加“当日报价” 我已经搜索了DRF文档,但没有找到任何关于如何做到这一点的内容 这是我的密码。项目序列化程序是: class ItemSerializer(serializers.ModelSer

是否有方法将自定义数据添加到使用Django REST Framework的ModelViewSet的视图的列表API调用返回的结果数据中

“我的模型视图集”视图附着到项目模型

除了listapi调用返回的项目列表之外,我还想查询一个单独的seed模型,并返回每个项目的查看次数

我还想在返回的数据中添加“当日报价”

我已经搜索了DRF文档,但没有找到任何关于如何做到这一点的内容

这是我的密码。项目序列化程序是:

class ItemSerializer(serializers.ModelSerializer):
username=serializers.SerializerMethodField()
def get_用户名(self,obj):
"""
请注意,可以按如下方式访问查询参数:
request=self.context['request']
打印请求。查询参数。获取['fields']
"""
值=str(对象所有者)
返回值
def get_关键字(自身、obj):
value=str(对象关键字)
返回值
类元:
型号=项目

字段=('id'、'url'、'item\u type'、'title'、'credits\u applicated'、'credits\u left'、'credits\u gifted'、'username'、'liked'、'disliked')
如果要将新数据附加到常规响应,可以执行以下操作:

class ItemViewSet(viewsets.ModelViewSet):
    ...

    def list(self, request, *args, **kwargs):
        custom_data = {
            'list_of_items': ItemSerializer(self.get_queryset(),many=true).data  # this is the default result you are getting today
            'quote_of_the_day': <code to compute Quote of the day>
            'number_of_times': <code to compute number of times>
        }
        return Response(custom_data)
    ...
class ItemViewSet(ViewSet.ModelViewSet):
...
def列表(自我、请求、*args、**kwargs):
自定义数据={
'list_of_items':ItemSerializer(self.get_queryset(),many=true)。data#这是您今天得到的默认结果
“当日报价”:<计算当日报价的代码>
“次数”:<计算次数的代码>
}
返回响应(自定义_数据)
...
尽管如此,根据您的评论判断:“每个项目已被查看的次数。”时间次数似乎是每个项目的新属性,因此您还可以执行以下操作:

class ItemViewSet(viewsets.ModelViewSet):
    ...

    def list(self, request, *args, **kwargs):
        custom_data = {
        'list_of_items': ItemSerializer(self.get_queryset(), many=true).data  # this is the default result you are getting today
         'quote_of_the_day': <code to compute Quote of the day>
        })
        return Response(custom_data)
...

class ItemSerializer(serializers.ModelSerializer):
    ...
    number_of_times = serializers.SerializerMethodField()
    ...

    def get_number_of_times(self):
        # compute and return the number of times the Item has been seen.
    ...
class ItemViewSet(ViewSet.ModelViewSet):
...
def列表(自我、请求、*args、**kwargs):
自定义数据={
'list_of_items':ItemSerializer(self.get_queryset(),many=true)。data#这是您今天得到的默认结果
“当日报价”:<计算当日报价的代码>
})
返回响应(自定义_数据)
...
类ItemSerializer(serializers.ModelSerializer):
...
次数=序列化程序。SerializerMethodField()
...
def获取次数(自我):
#计算并返回项目已被查看的次数。
...

如果使用分页器,则可以使用:

from collections import OrderedDict

from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
from rest_framework import viewsets

class CustomLimitOffsetPagination(LimitOffsetPagination):

    def get_paginated_response(self, data):

        return Response(
            OrderedDict([
                ('count', self.count),
                ('next', self.get_next_link()),
                ('previous', self.get_previous_link()),
                ('results', data),
                ('extra_field', <your_value>),
            ]))

class SomeViewset(viewsets.ModelViewSet):
    pagination_class = CustomLimitOffsetPagination
从集合导入订单数据
从rest_framework.pagination导入限制OffsetPagination
来自rest\u framework.response导入响应
从rest\U框架导入视图集
类CustomLimitOffsetPagination(LimitOffsetPagination):
def获取分页的应答(自身、数据):
返回响应(
有序的([
('count',self.count),
('next',self.get_next_link()),
('previous',self.get_previous_link()),
(“结果”,数据),
(‘额外_字段’,),
]))
类SomeViewset(ViewSet.ModelViewSet):
分页\u class=CustomLimitOffsetPagination

您能告诉我任何示例代码吗?我想不出怎么做。我已经有了一个标准列表结果的序列化程序。你能提供相关的模型和序列化程序吗?然后我可以帮你定制谢谢@trinchet我已经在问题中添加了我的代码。希望它现在更有意义!是的,我现在有了一个更好的主意,我已经更新了我的回复,给了你两种可能的方法。我是否需要向ItemSerializer类元字段添加“次数”?