【问题标题】:How can I store a non-unicode string in the database of my Django App?如何在我的 Django 应用程序的数据库中存储非 unicode 字符串?
【发布时间】:2011-04-26 16:26:15
【问题描述】:

我正在尝试访问views.py 中的一个字段,以便对其执行一项操作,该操作将计算其与用户输入点的距离(使用geopy)。输入需要是纯字符串,但当前存储在我的数据库中为:u'(lat, lng)' geopy 不喜欢。

如何以正确的格式(例如 (lat, lng) )将信息存储在我的数据库中。坐标最初是以这种格式输入的。

提前感谢您,对于没有使用正确的术语表示歉意,这是新手和自学的。

【问题讨论】:

    标签: django django-models django-views geopy


    【解决方案1】:

    使用 django 烦人

    class MyModel(models.Model):
        ...
        lat_lng = JsonField()
    

    并存储:

    MyModel.objects.create(lat_lng={'data': (lat, lng)}, ...)
    

    并使用:

    my_model_object.lat_lng['data']
    

    【讨论】:

      【解决方案2】:

      你是说表中存储的实际值是u'(lat, lng)'?您是否在存储之前将字符串转换为另一种表示形式?这看起来不对。

      如有必要,您可以更改表格使用的编码。在这里阅读:How to set the encoding for the tables' char columns in django?

      您还可以在 python 中使用之前将encode/decode 字符串转换为特定字符集:What is the difference between encode/decode?

      【讨论】:

      • 我不太确定您的意思是“在存储之前将字符串转换为另一种表示形式”,但听起来可能就是这种情况。这是我得到的class Place(models.Model): coordinates = models.CharField(max_length=60) def save(self, *args, **kwargs): self.coordinates = Location(self.zipcode, self.street) super(Venue, self).save(*args, **kwargs) 然后我尝试访问 views.py 中的坐标(用于计算两组坐标之间距离的方法),但得到 u'(lat, lng) 作为我的输出
      猜你喜欢
      • 2012-03-04
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-31
      • 2017-11-23
      • 2019-08-22
      • 1970-01-01
      相关资源
      最近更新 更多