I'm new to DRF and have just started building an API.
我是DRF的新手,刚刚开始构建API。
I've a model called Shop. And I've two user different user types : Customer and Supplier.
我有一个名为Shop的模特。我有两种用户不同的用户类型:客户和供应商。
- I want to add a custom field distance to the response of the GET request /shops/id/, which represents the distance between the Customer that is submitted the request and the corresponding shop.
- I think I cannot use SerializerMethodField since the value of the method is not only depend on the object itself.
- I do not want to add this custom field for all GET requests, instead, I need to add it, when the user that is submitted the request is a Customer.
我想在GET请求/商店/ id /的响应中添加自定义字段距离,该距离表示提交请求的客户与相应商店之间的距离。
我想我不能使用SerializerMethodField,因为该方法的值不仅取决于对象本身。
我不想为所有GET请求添加此自定义字段,而是在提交请求的用户是Customer时我需要添加它。
Considering constraints above, how should I add the custom field to the response of the request? What's the best way to do this ?
考虑到上述约束,我应该如何将自定义字段添加到请求的响应中?最好的方法是什么?
1 个解决方案
#1
5
You can define a distance
SerializerMethodField
, and there access the current user location using serializer's context
. Then compute distance using current user location and shop's location.
您可以定义距离SerializerMethodField,并使用序列化程序的上下文访问当前用户位置。然后使用当前用户位置和商店位置计算距离。
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
#1
5
You can define a distance
SerializerMethodField
, and there access the current user location using serializer's context
. Then compute distance using current user location and shop's location.
您可以定义距离SerializerMethodField,并使用序列化程序的上下文访问当前用户位置。然后使用当前用户位置和商店位置计算距离。
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