如何从django-mapbox LocationField提取经纬度 解决tuple无y属性报错
报错根因
mapbox_location_field 的 LocationField 在模型实例中默认存储的是 (经度, 纬度) 格式的二元元组,并非带有 .x、.y 属性的地理点对象,直接调用对应属性就会触发 'tuple' object has no attribute 'y' 错误。
修正实现
调整模型 save 方法,通过元组索引提取经纬度,同时增加结构校验避免异常值触发报错,修正后的代码如下:
from django.db import models from django.contrib.auth.models import User from mapbox_location_field.models import LocationField class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, blank=True, null=True) location = LocationField(null=True, blank=True) latitude = models.DecimalField(max_digits=20, decimal_places=18, null=True, blank=True) longitude = models.DecimalField(max_digits=20, decimal_places=18, null=True, blank=True) # 原代码__str__引用了未定义的store_name字段,需补充对应字段或修改返回逻辑 # store_name = models.CharField(max_length=100, verbose_name="门店名称") def __str__(self): return self.store_name def save(self, *args, **kwargs): # 校验location为合法二元经纬度结构 if self.location and isinstance(self.location, (tuple, list)) and len(self.location) == 2: # 元组固定顺序为 (经度, 纬度),分别对应longitude、latitude字段 self.longitude = self.location[0] self.latitude = self.location[1] super(Profile, self).save(*args, **kwargs)
补充说明
- 若使用的是较新版本的
mapbox_location_field,可先通过print(type(self.location), self.location)确认存储结构,部分版本会返回自定义Location对象,这类场景才支持用.x、.y属性取值。 - 当前配置的经纬度字段精度完全满足常规存储需求,无需调整。
内容的提问来源于stack exchange,提问作者mehdi
相关产品推荐
相关产品推荐

