Search code examples
pythondjangodistancegeogeodjango

GeoDjango how to display distance in meters in this query


GeoDjango how to display distance in meters in this query

Right now I'm just displaying them by distance ranking.

I would like to get the distance in meters more

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}, )

I would like to get the distance in meters more

Thanks friends/謝謝朋友/Gracias amigos/Danke Freunde/Merci les amis/धन्यवाद दोस्तों/Спасибо друзья


Solution

  • This is similar (but not direct duplicate it believe) to this question: Django django.contrib.gis.db.models.functions.Distance to return values in feet instead of meters

    Django's Distance documentation state the following:

    Because the distance attribute is a Distance object, you can easily express the value in the units of your choice. For example, city.distance.mi is the distance value in miles and city.distance.km is the distance value in kilometers. See Measurement Objects for usage details and the list of Supported units. quote

    Therefore, in order to express the distance in meters you can modify the query as follows:

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