我使用DjangoRestFramework并且有一个queryset,它返回通用ListAPIView的对象。我想遍历查询集中的每个对象并运行下面的代码来使用geopy distance.distance计算距离值,然后将其添加为临时字段,以便稍后我可以根据此新的距离字段过滤查询集。
目前我有以下代码,但它似乎没有保存新的临时字段address.distance,我想在显示每个对象的新距离值时返回新的查询集
在views.py中:
class business_list(generics.ListAPIView):
serializer_class = BusinessSerializer
@csrf_exempt
def get_queryset(self):
"""
List all businesses.
"""
queryset = Business.objects.all()
distanceParam = self.request.QUERY_PARAMS.get('distance', None)
locationParam = self.request.QUERY_PARAMS.get('location', None)
if distanceParam is not None and locationParam is not None:
for business in queryset:
storelocations = ()
for location in business.locations.all():
long = location.address.all()[:1].get().long
lat = location.address.all()[:1].get().lat
businessCoords = (lat, long)
testCoords = (40.795745, -73.948646)
address = location.address.all()[:1].get()
address_two = location.address.all()[:1].get()
address.distance = distance.distance(businessCoords, testCoords).miles
# my_obj_list = list(address, address_two)
# queryset = my_obj_list
# wd = Business.objects.annotate(distance="lol")
# queryset = wd
return queryset