GeoDjango如何在此查询中以米为单位显示距离



GeoDjango如何在此查询中以米为单位显示距离

现在我只是按距离排序来显示它们。

我想再得到以米为单位的距离

models.py

class Master(models.Model):
city_master = models.ForeignKey(myCity, on_delete=models.CASCADE, null=True, blank=True, verbose_name="cityName", db_index=True, related_name="CityName_relate")
country_master = models.ForeignKey(CountryMy, on_delete=models.CASCADE, null=True, blank=True, verbose_name="countryName", db_index=True, related_name="CountryMyName_relate")
name = models.CharField(blank=True, null=True, max_length=3000)
point = models.PointField(blank=True, null=True)

views.py

from django.contrib.gis.db.models.functions import Distance
class MainList(View):
.....
def get(self, request):
........
current_location = BaseUrl.objects.get(Country__nameCountry_for_sites=str(country)).point
main_masters_in_country = myCity.objects.filter(
point__distance_lte=((current_location, D(km=50)))).annotate(
distance=Distance('point', current_location)).order_by('distance')[:5]

return render(request, self.template_name, context={'main_masters_in_country': main_masters_in_country}, )

我想再得到以米为单位的距离

谢谢朋友/謝謝朋友/谢谢朋友谢谢Freunde/谢谢les ami/धन्यवाददोस्तों/Спасибодрузья

这与这个问题类似(但不是直接复制):Django Django .contrib.gis.db.models.functions. distance返回以英尺为单位的值,而不是以米为单位

Django的Distance文档说明如下:

因为距离属性是一个Distance对象,所以您可以很容易地用您选择的单位表示该值。例如,city.distance.mi表示距离值,单位为英里,city.distance.km表示距离值,单位为公里。有关使用细节和支持的单位列表,请参阅测量对象。引用

因此,为了表示以米为单位的距离,可以对查询进行如下修改:

(...).annotate(
distance=Distance('point', current_location).m
).order_by('distance')[:5]

最新更新