如何舍入 Geodjango 距离

How to round a Geodjango Distance

在 Django 1.9 / Python 2.7 中,我有以下观点:

qs = ThePlace.objects.filter(lnglat__distance_lte=(lnglat, D(km=30))).distance(lnglat).order_by('distance')

在我的模板中,当我遍历对象时显示距离:

{% for qsplace in qs %}
    {{ qsplace.distance }}
{% endfor %}

例如显示“25.717617095 m”。

我想显示四舍五入的数字 (26 m)。如果超过1公里,我想显示3公里例如

我开发了第一个四舍五入的模板标签:

from django import template
register = template.Library()

@register.filter
def dividebyth(value):
    print(type(value))
    value = round(value, 2)
    return value

并放入我的模板: {{ qsplace.distance|dividebyth }}

这会导致以下错误:

TypeError: a float is required

看来我无法舍入距离对象。

有什么方法可以解决吗?

谢谢!

来自 docs

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.

要获取以米为单位的浮动距离值,试试这个:{{ qsplace.distance.m|dividebyth }}