[英]Django Rest Framework : How to add a custom field to the response of the GET request?
I'm new to DRF and have just started building an API. 我是DRF的新手,刚刚开始构建API。
I've a model called Shop . 我有一个名为Shop的模型。 And I've two user different user types : Customer and Supplier .
我有两个用户不同的用户类型: 客户和供应商 。
Considering constraints above, how should I add the custom field to the response of the request? 考虑到以上约束,我应该如何将自定义字段添加到请求的响应中? What's the best way to do this ?
最好的方法是什么?
You can define a distance
SerializerMethodField
, and there access the current user location using serializer's context
. 您可以定义一个
distance
SerializerMethodField
,然后使用serializer的context
访问当前用户位置。 Then compute distance using current user location and shop's location. 然后使用当前用户位置和商店位置计算距离。
class ShopSerializer(serializers.ModelSerializer):
distance = serializers.SerializerMethodField()
class Meta:
model = Shop
fields = (.., 'distance')
def get_distance(self, obj):
current_user = self.context['request'].user # access current user
user_location = current_user.location
distance = <compute distance using obj.location and user_location>
return distance
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.