簡體   English   中英

Django Rest Framework:如何在GET請求的響應中添加自定義字段?

[英]Django Rest Framework : How to add a custom field to the response of the GET request?

我是DRF的新手,剛剛開始構建API。

我有一個名為Shop的模型。 我有兩個用戶不同的用戶類型: 客戶供應商

  1. 我想在GET請求/ shops / id /的響應中添加一個自定義字段距離 ,該距離代表提交請求的客戶與相應商店之間的距離。
  2. 我認為我不能使用SerializerMethodField,因為方法的值不僅取決於對象本身。
  3. 我不想為所有GET請求添加此自定義字段,而是在提交請求的用戶是Customer時添加它。

考慮到以上約束,我應該如何將自定義字段添加到請求的響應中? 最好的方法是什么?

您可以定義一個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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM