Heroku上的Djangohstore

2024-04-24 15:24:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Heroku(雪松堆栈)上部署了一个Django(v1.3.3)项目。它使用推荐的dj_database_url进行配置settings.数据库. 一切都很好(到目前为止)。在

但是,我想开始在应用程序的一部分使用django-hstore。根据文档,您必须在设置.py收件人:

'ENGINE': 'django_hstore.postgresql_psycopg2',

因此,在我的设置.py我要做的是:

^{pr2}$

对我来说,在当地一切都很好。我的模型有hstore字段,工作很好(值就是字典)。在

但是,当我部署到Heroku时,数据库引擎将重置/重写为:

ENGINE: 'django.db.backends.postgresql_psycopg2'

为了调试它,我在设置文件中设置了引擎后进行了打印。然后,我运行bash:

heroku run bash

然后:

python myapp/manage.py shell

当我运行这个程序时,print语句显示了所需引擎(django)的正确(所需)数据库设置_hstore.postgresql_psycopg2). 但是,如果我这样做了:

from django.conf import settings
print settings.DATABASES

我可以看到数据库引擎不再是django_hstore,而是设置回正常(非hstore)值。如果我导入一个模型并执行get来加载一个对象,hstore字段中的值是一个字符串,任何访问键的尝试都会抛出错误:

TypeError: string indices must be integers, not str

请记住,这件作品是在当地找到的。但是,在部署到heroku之后,任何作为字典访问值的尝试都会抛出上面的TypeError。在

我的问题是:

  • 有人知道为什么我的引擎被超越了吗?如果是这样的话,我该怎么解决呢?在

或者

  • 有没有其他方法可以在Django 1.3.3中使用hstore字段,而不需要更改引擎(因此对Heroku更友好一点)

Tags: djangopy模型引擎bash数据库heroku字典
3条回答

很高兴地告诉你django_hstore的新版本1.2.1已经发布

通过pip升级并检查新的官方django hstore github存储库:https://github.com/djangonauts/django-hstore

SQLAlchemy 0.8包含可用于创建custom model的实用程序方法,用于处理Pythondict和Postgreshstore之间的转换。在

from django.db import models
from sqlalchemy.dialects.postgresql.hstore import _parse_hstore, _serialize_hstore

class HStoreField (models.TextField):
    __metaclass__ = models.SubfieldBase

    def __init__(self, *args, **kwargs):
        super(HStoreField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if value is None:
            return None
        if isinstance(value, dict):
            return value
        return _parse_hstore(value)

    def get_db_prep_save(self, value, connection):
        if value is None:
            return None
        if isinstance(value, str):
            return value
        return _serialize_hstore(value)

    def db_type (self, connection):
         return "hstore"

这个模型是可移植的,但是如果您想运行基于hstore键或值的查询,则必须用原始SQL编写它们。在

我使用SQLite内存数据库来运行测试,只要对非PostgreSQL后端使用text类型,它就可以正常工作:

^{pr2}$

https://github.com/niwibe/djorm-ext-hstore

看起来这个包最初是django hstore的一个分支,包含相同的功能,但是已经更新为不再需要定制的数据库后端,这看起来可以缓解您的问题。(请注意,其中的一些查询语法已更改)。在

作为一个额外的好处,回购的维护时间比你链接的original django-hstore要晚得多,这已经多年没人碰过了。。。吓人的。在

相关问题 更多 >