![](/img/trans.png)
[英]Add custom data in Response() of django rest framework while GET?
[英]Django Rest Framework : How to add a custom field to the response of the GET request?
我是DRF的新手,剛剛開始構建API。
我有一個名為Shop的模型。 我有兩個用戶不同的用戶類型: 客戶和供應商 。
考慮到以上約束,我應該如何將自定義字段添加到請求的響應中? 最好的方法是什么?
您可以定義一個distance
SerializerMethodField
,然后使用serializer的context
訪問當前用戶位置。 然后使用當前用戶位置和商店位置計算距離。
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.