[Django]-Django-hstore on Heroku

2👍

SQLAlchemy 0.8 includes utility methods that can be used to create a custom model for handling the conversion between Python dict and Postgres hstore.

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"

This model is portable, but if you want to run queries based on hstore keys or values you’ll have to write them in raw SQL.

I use an SQLite in-memory database for running tests, which works fine as long as you use the text type for non-PostgreSQL backends:

    def db_type (self, connection):
        from django.db import connection
        if connection.settings_dict['ENGINE'] == \
            'django.db.backends.postgresql_psycopg2':
            return "hstore"
        else:
            return "text"

1👍

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

Looks like this package was originally a fork of django-hstore and includes the same functionality, but has been updated to no longer require a custom Database backend which would appear to alleviate your problem. (Note that some of the query syntax has changed in it).

As a bonus, the repo is maintained much more recently than the original django-hstore you link to, which hasn’t been touched in years… scary.

1👍

happy to tell you the new version 1.2.1 of django_hstore is out

Upgrade via pip and check the new official django-hstore github repository: https://github.com/djangonauts/django-hstore

Leave a comment