Django django.contrib.gis.db.models.functions.Distance 到 return 值以英尺而不是米为单位
Django django.contrib.gis.db.models.functions.Distance to return values in feet instead of meters
以下代码将正确过滤:
def nearby(self, latitude, longitude, proximity=None):
"""Get nearby Merchants.
Custom queryset method for getting merchants associated with
nearby places.
Returns:
A queryset of ``Merchant`` objects.
"""
point = Point(latitude, longitude)
# we query for location nearby for places first and then
# annotate with distance to the same place
return self.filter(
places__location__distance_lte=(point, D(ft=proximity))
).annotate(distance=models.Min(Distance('places__location', point)))
但是
返回的值
models.Min(Distance('places__location', point))
以米为单位。
能不能换成英尺?
如果我们看一下 Distance
documentation,我们会看到:
Because the distance attribute is a Distance object, you can easily express the value in the units of your choice.
虽然这不是:
Those two aren't that closely related to each other. Docs do indeed say that it "returns" Distance object, but there is an extra step:
django.contrib.gis.db.models.functions.Distance
is a database function, it takes two expressions (that may include database field names) and returns a Func
object that can be used as a part of a query.
So simply put, it needs to be executed in a database. It will calculate distance using database function (e.g. postgis ST_Distance) and then bring it back as a django.contrib.gis.measure.Distance
object
综上所述,你可以这样做:
... .annotate(distance=models.Min(Distance('places__location', point).ft))
以下代码将正确过滤:
def nearby(self, latitude, longitude, proximity=None):
"""Get nearby Merchants.
Custom queryset method for getting merchants associated with
nearby places.
Returns:
A queryset of ``Merchant`` objects.
"""
point = Point(latitude, longitude)
# we query for location nearby for places first and then
# annotate with distance to the same place
return self.filter(
places__location__distance_lte=(point, D(ft=proximity))
).annotate(distance=models.Min(Distance('places__location', point)))
但是
返回的值models.Min(Distance('places__location', point))
以米为单位。
能不能换成英尺?
如果我们看一下 Distance
documentation,我们会看到:
Because the distance attribute is a Distance object, you can easily express the value in the units of your choice.
虽然这不是
Those two aren't that closely related to each other. Docs do indeed say that it "returns" Distance object, but there is an extra step:
django.contrib.gis.db.models.functions.Distance
is a database function, it takes two expressions (that may include database field names) and returns aFunc
object that can be used as a part of a query.So simply put, it needs to be executed in a database. It will calculate distance using database function (e.g. postgis ST_Distance) and then bring it back as a
django.contrib.gis.measure.Distance
object
综上所述,你可以这样做:
... .annotate(distance=models.Min(Distance('places__location', point).ft))