【问题标题】:Why I am getting value error in my location finding function?为什么我的位置查找功能出现值错误?
【发布时间】:2018-06-20 10:52:56
【问题描述】:

我需要你的帮助来找出我的代码中的错误。

我正在尝试在用户输入地址后自动填充纬度/经度字段。因此,位置字段地图将显示,并且两个字段都将自动填充。

models.py:

from location_field.models.plain import PlainLocationField
class Store(models.Model):
    building = models.ForeignKey(Building, related_name='building', on_delete=models.SET_NULL, blank=True, null=True)
    address = models.TextField(default='Singapore')
    latitude = models.FloatField(validators=[MinValueValidator(-90.0), MaxValueValidator(90.0)])
    longitude = models.FloatField(validators=[MinValueValidator(-180.0), MaxValueValidator(180.0)])
    location = PlainLocationField(based_fields=['address'], zoom=7, null=True)

    @property
    def latitude(self):
        if not self.location:
            return
        try:
            print('Store Location1: ' + str(self.location))
            latitude, _ = self.location.split(',')
        except Exception as e:
            print('Exception1: ' + str(e))
        print("latitude:", latitude)
        return latitude

    @property
    def longitude(self):
        if not self.location:
            return
        try:
            print('Store Location2: ' + str(self.location))
            _, longitude = self.location.split(',')
        except Exception as e:
            print('Exception2: ' + str(e))
        print("longitude:", longitude)
        return longitude

当启动我的服务器时,我看到以下两个打印语句-

Store Location1: 8 SHENTON WAY #43-01 AXA TOWER Singapore
Exception1: not enough values to unpack (expected 2, got 1)

从不打印经度函数中的打印语句。当我去我的商店时,它在浏览器中显示以下错误-

File "E:\mysite\models.py", line 216, in latitude
latitude, _ = self.location.split(',')
Exception Type: ValueError
Exception Value:not enough values to unpack (expected 2, got 1)

谁能帮我找出确切的问题?

【问题讨论】:

  • 在您打印的字符串中,没有逗号。所以用逗号分割字符串会得到一个单一元素的列表,不能解包成两个变量。
  • 谢谢,我明白了,这是我的错误。那么您能告诉我如何更改我的功能代码以使其正常工作吗?
  • 完全不相关,但您的 latitude 和 longitude 属性会影响同名字段。
  • @brunodesthuilliers 我同意,我将从代码和数据库中删除这两个属性。

标签: python python-3.x django-2.0


【解决方案1】:

您不能将大小为 1 的可迭代对象解压缩为两个变量。这是您的问题的最小示例。

mystr = 'Store Location1: 8 SHENTON WAY #43-01 AXA TOWER Singapore'

latitude, _ = mystr.split(',')

# ValueError: not enough values to unpack (expected 2, got 1)

请注意,您的输入字符串中没有逗号。因此,您需要重构逻辑或确保上游数据合适。

例如,如果您希望location 仅代表第一个拆分:

latitude = mystr.split(', ', 1)[0]

【讨论】:

  • 谢谢 jpp,我明白了,这是我的错误。那么您能告诉我如何更改我的功能代码以使其正常工作吗?
  • 我的意思是要更改我的纬度和经度函数。是否需要同时删除两者?
  • @AnalyticsPy,恐怕这远远超出了解决您的错误的范围。要修复您的工作流程,我需要使用 minimal reproducible example。如果无法做到这一点,请随时等待。
  • 这是我的错。您提到的纬度更改现在有效,经度我该怎么办?
  • @AnalyticsPy,我怀疑问题类似。要识别问题,事先print字符串,如果不能被,分割,那就找出你需要的东西,改变你的逻辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 2023-01-26
  • 2020-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多