如何在 drf api 响应中获取距离?
how to get distance in drf api response?
我有 与 this SO question 完全相同 的问题(很抱歉 link 并且没有再写完整的内容。)
此外,我已经实现了针对相同问题给出的solution。
但我在 API 响应中没有收到 distance
。我没有在序列化程序字段中添加 distance
,所以它不会出现在响应中。但是当我将它添加到字段时,出现以下错误。
Field name distance is not valid for model Address.
我也尝试编写一个序列化程序方法字段,但不确定如何将查询参数中接收到的位置传递给序列化程序进行比较。
所以问题是应该如何在 API 响应中发送距离?
如果您使用 distance
字段注释您的查询集,您还需要编辑序列化程序以包含该特定字段:
class AddressSerializer(serializers.ModelSerializer):
#...
distance = serializers.DecimalField(max_digits=10, decimal_places=2)
#...
class Meta:
model = Address
fields = ('distance', ) #add other fields you need
我有 与 this SO question 完全相同 的问题(很抱歉 link 并且没有再写完整的内容。)
此外,我已经实现了针对相同问题给出的solution。
但我在 API 响应中没有收到 distance
。我没有在序列化程序字段中添加 distance
,所以它不会出现在响应中。但是当我将它添加到字段时,出现以下错误。
Field name distance is not valid for model Address.
我也尝试编写一个序列化程序方法字段,但不确定如何将查询参数中接收到的位置传递给序列化程序进行比较。
所以问题是应该如何在 API 响应中发送距离?
如果您使用 distance
字段注释您的查询集,您还需要编辑序列化程序以包含该特定字段:
class AddressSerializer(serializers.ModelSerializer):
#...
distance = serializers.DecimalField(max_digits=10, decimal_places=2)
#...
class Meta:
model = Address
fields = ('distance', ) #add other fields you need