为整个结果集向Django Rest Framework结果添加额外的数据 [英] Adding extra data to Django Rest Framework results for entire result set

查看:181
本文介绍了为整个结果集向Django Rest Framework结果添加额外的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django Rest Framework,并且需要向结果集中添加额外的数据。具体来说,通常您会在哪里:

I'm using Django Rest Framework and need to add extra data to a result set. Specifically, where you would usually have:

{
    "count": 45, 
    "next": "http://localhost:8000/foo/bar?page=2", 
    "previous": null, 
    "results": [
        {...}
    ]
}

我想添加一些额外的计数,例如:

I would like to add extra counts like so:

{
    "count": 45,
    "10_mi_count": 10,
    "20_mi_count": 30,
    "30_mi_count": 45,
    "next": "http://localhost:8000/foo/bar?page=2", 
    "previous": null, 
    "results": [
        {...}
    ]
}

此示例中的额外计数是多少个对象的视场距离值小于键中描述的英里。

The extra counts in this example are just how many of the objects have a field distance with a value less than the miles described in the key.

我的问题是我不知道扩展和插入此行为的最佳位置在哪里。

My issue is that I have no idea where the best place to extend and insert this behaviour is.

理想情况下,无论结果是否分页,我都希望此方法能够起作用没有任何假设。

Ideally I'd like this to work whether or not the results are paginated, making no assumptions.

我在这里真正想得到的是朝着正确方向点头(以及为什么这是正确的去处)。

What I'm really after here is a nod in the right direction (and why that is the right place for it go).

我检查了文档,找不到任何描述如何添加类似内容的内容,但我很乐意在该分数上被证明是错误的。

I've checked the docs and can't find anything that describes how to add things like this, but I would be more than happy to be proven wrong on that score.

推荐答案

由于您似乎正在使用Rest Framework中的ListView之一,因此可以覆盖类中的list()方法并在结果数据上设置新值,像这样:

Since you seem to be using one of the ListViews from the Rest Framework, you could override the list() method in your class and set new values on the resulting data, like this:

    def list(self, request, *args, **kwargs):
        response = super().list(request, args, kwargs)
        # Add data to response.data Example for your object:
        response.data['10_mi_count'] = 10 # Or wherever you get this values from
        response.data['20_mi_count'] = 30
        response.data['30_mi_count'] = 45
        return response

请注意,您的类必须继承List直接或通过Rest Framework API( http:/ /www.django-rest-framework.org/api-guide/generic-views#listmodelmixin )。我真的不知道这样做是否正确,但这是一个快速解决方案。

Notice that your class must inherit the ListModelMixin directly or via a GenericView from the Rest Framework API (http://www.django-rest-framework.org/api-guide/generic-views#listmodelmixin). I really don't know if it is the right way to do this, but it is a quick fix.

希望它会有所帮助!

这篇关于为整个结果集向Django Rest Framework结果添加额外的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆