将额外字段添加到序列化器中,而无需添加到模型中 - python

我一直在尝试将字段“距离”添加到结果中包含的字段中。但是,该字段不在模型或序列化器中,我只是想知道返回此类字段的最佳方法是什么?任何帮助是极大的赞赏。谢谢!

视图是:

class PlaceViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows places to be viewed or edited.
    """

    current_lat = 54.52984
    current_lon = -1.5609

    """
    Haversine formula used to sort places by distance (closest first).
    """
    query = "select distinct id, (((acos(sin((" + format(current_lat) + \
            "*pi()/180)) * sin((lat*pi()/180))+cos((" + format(current_lat) + \
            "*pi()/180)) * cos((lat*pi()/180)) * cos(((" + format(current_lon) + \
            " - lon)*pi()/180))))*180/pi())*60*1.1515) AS distance " \
            "from mobileapi_place " \
            "order by distance asc"

    queryset = Place.objects.raw(query)
    serializer_class = PlaceSerializer

下面是序列化器。

class PlaceSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Place
        fields = ('title', 'lat', 'lon', 'featured_image_url', 'created_at')

参考方案

您是否尝试过SerializerMethodField

应该是这样的。

class PlaceSerializer(serializers.HyperlinkedModelSerializer):
    distance = SerializerMethodField()

    class Meta:
        model = Place
        fields = ('title', 'lat', 'lon', 'distance', 'featured_image_url', 'created_at')

    def get_distance(self, obj):
        return obj.distance

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

您如何在列表内部调用一个字符串位置? - python

我一直在做迷宫游戏。我首先决定制作一个迷你教程。游戏开发才刚刚开始,现在我正在尝试使其向上发展。我正在尝试更改PlayerAre变量,但是它不起作用。我试过放在列表内和列表外。maze = ["o","*","*","*","*","*",…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。