如何在 Django 中人性化测量查询
How to humanize measurement queries in Django
我在 Django 中有一个距离查询,并打印了一个有几个小数点的距离。它以 1023.40258027906 m 的测量格式显示距离。我想让这个人类可读。我尝试使用 Decimal 但这失败了,因为它不适用于测量对象。测量对象是带有 km、m、cm 等标签的距离对象。通过人性化,我的意思是不超过 2 或 3 个小数位。这些是从
进口的
from django.contrib.gis.measure import D
from django.contrib.gis.db.models.functions import Distance
这是用于生成距离测量值的查询集。
查询集:
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>
如果您想将值四舍五入到特定精度,您可以使用 floatformat
template filter [Django docs] 来执行此操作。
由于距离是来自 django.contrib.gis.measure
的 Distance
对象,您可以通过编写 distance.<format_name>
以您喜欢的格式获取距离,例如distance.m
然后你可以在上面使用 floatformat
:
<!-- round to 3 decimal places -->
{{ apartment.distance.m|floatformat:3 }} m
上面链接的文档中显示了更多配置此过滤器输出的方法。
我在 Django 中有一个距离查询,并打印了一个有几个小数点的距离。它以 1023.40258027906 m 的测量格式显示距离。我想让这个人类可读。我尝试使用 Decimal 但这失败了,因为它不适用于测量对象。测量对象是带有 km、m、cm 等标签的距离对象。通过人性化,我的意思是不超过 2 或 3 个小数位。这些是从
进口的from django.contrib.gis.measure import D
from django.contrib.gis.db.models.functions import Distance
这是用于生成距离测量值的查询集。 查询集:
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>
如果您想将值四舍五入到特定精度,您可以使用 floatformat
template filter [Django docs] 来执行此操作。
由于距离是来自 django.contrib.gis.measure
的 Distance
对象,您可以通过编写 distance.<format_name>
以您喜欢的格式获取距离,例如distance.m
然后你可以在上面使用 floatformat
:
<!-- round to 3 decimal places -->
{{ apartment.distance.m|floatformat:3 }} m
上面链接的文档中显示了更多配置此过滤器输出的方法。