I have a distance query in Django and prints a distance with several decimal points. It displays distance in a measurement format as 1023.40258027906 m .I want to make this human readable. I tried using Decimal but this failed as it does not apply to measurement objects. Measurement objects are distance objects with labels like km, m, cm. By humanize, I mean not more than 2 or 3 decimal digits. These are import from
from django.contrib.gis.measure import D
from django.contrib.gis.db.models.functions import Distance
Here is the Queryset used to generate the distance measurements. Queryset:
queryset = Apartment.objects.filter(geom__distance_lte=(user_location, D(km=2))).annotate(distance=Distance('geom', user_location))
<style type="text/css">
ul{
list-style-type: circle;
margin:0px;
padding-left: 1em;
}
</style>
<head>
</head>
<body><strong>Nearby Apartments</strong>
{% if apartments %}
<ul>
{% for apartment in apartments %}
<li>
{{ apartment.apt_id }}: {{apartment.distance}}
</li>
{% endfor %}
</ul>
{% endif %}
</div>
</body>
If you want to round the value to a specific precision you can use the floatformat
template filter [Django docs] to do this.
Since the distance is a Distance
object from django.contrib.gis.measure
you can get the distance in your preferred format by writing distance.<format_name>
e.g. distance.m
and then you can use floatformat
on that:
<!-- round to 3 decimal places -->
{{ apartment.distance.m|floatformat:3 }} m
There are more ways to configure the output of this filter which are shown in the documentation linked above.