Django结合Geopy:如何为每条帖子匹配对应的专属用户距离
问题根因定位
- 目前将距离计算结果单独存为独立的
distance列表,和帖子查询集没有做任何关联绑定。如果模板中在循环渲染单条帖子的代码块里直接输出{{ distance }},就会把整个列表原样渲染出来,自然出现每条帖子都展示全量距离值、跨帖子重复错位的问题。 - 原循环逻辑中,每遍历一条帖子就重新查询一次当前用户的UserProfile数据,既浪费数据库查询性能,也容易因重复查询时机问题出现取值偏移。
- 原代码存在分支覆盖漏洞:当用户未登录、或登录但
userprofile.full_address为空时,distance变量从未被定义,传递到模板时会直接触发上下文变量未定义的错误。
具体调试修改方案
视图层逻辑调整(完全保留原有业务逻辑、模型定义,仅补全关联绑定)
首先将用户坐标查询提到循环外部,减少重复查询;再把计算得到的距离直接挂载到每个Cuisine对象实例上,实现对象和距离值的一一绑定,同时修正Geopy坐标顺序的传参错误:
def Homemainpage(request): post = Cuisine.objects.filter(status=0).order_by('-publishing_date').all() # 初始化用户坐标变量,避免分支遗漏导致变量未定义报错 user_lat = None user_lon = None # 满足登录、有完整地址条件时读取用户坐标 if request.user.is_authenticated and request.user.userprofile.full_address: user_profile = request.user.userprofile user_lat = user_profile.latitude user_lon = user_profile.longitude # 遍历所有帖子,给每个帖子对象绑定对应计算的距离值 for p in post: if user_lat is not None and user_lon is not None: # 注意:Geopy geodesic 要求参数顺序为(纬度, 经度),原代码坐标传反会导致计算结果错误 post_situation = (p.latitude_user, p.longitude_user) user_situation = (user_lat, user_lon) p.calculated_distance = round(geodesic(post_situation, user_situation).km, 3) else: p.calculated_distance = None paginator = Paginator(post, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) listaliments = ListAliments.objects.filter(status=1).all() typerepas = Typerepas.objects.filter(status=1).all() sperepas = Sperepas.objects.filter(status=1).all() return render(request, 'index.html', { 'post': post, 'listaliments': listaliments, 'typerepas': typerepas, 'sperepas': sperepas, 'page_obj': page_obj, 'today' : now().date(), 'tomorrow': now().date() + timedelta(days=1), })
模板层修正
检查模板中遍历帖子的代码块,删除原来错误的{{ distance }}渲染代码(这是单条帖子直接展示全量距离列表的直接原因),替换为读取当前遍历的帖子实例上绑定的专属距离值即可:
{% for p in page_obj %} {# 原错误写法:直接输出独立的distance列表,导致每条帖子都展示全量值 #} {# 距离:{{ distance }} km #} {# 修正后写法:读取当前帖子对象上绑定的专属距离值 #} {% if p.calculated_distance is not None %} 距离:{{ p.calculated_distance }} km {% else %} 距离未知 {% endif %} {% endfor %}
避坑提示
- 不要在Django模板中通过列表索引平行匹配
post和distance两个独立列表的取值,一旦后续调整分页、排序、过滤逻辑,两个列表的顺序一旦错位,马上又会出现距离和帖子不匹配的问题。直接把值绑定到对象实例上是最稳妥的一一关联方案。 - 原代码中
UserProfile.objects.filter(user=request.user)[0]的写法,如果遇到用户没有对应UserProfile记录的场景,会直接抛出索引越界错误,直接通过Django自动关联的request.user.userprofile外键取值更稳妥。 - Geopy的
geodesic方法要求坐标参数顺序为(纬度, 经度),原代码将顺序写反为(经度, 纬度),就算解决了绑定错位的问题,计算得到的距离值也是完全错误的,必须调整参数顺序。
内容的提问来源于stack exchange,提问作者Louis
相关产品推荐
相关产品推荐

