gpt4 book ai didi

python - 在序列化器中添加一个额外的字段,但它不在模型中

转载 作者:太空宇宙 更新时间:2023-11-03 21:13:58 25 4
gpt4 key购买 nike

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

View 是:

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

关于python - 在序列化器中添加一个额外的字段,但它不在模型中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54850424/

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