如何使用由南方管理的现有应用程序设置django-hstore?

问题描述 投票:21回答:3

我尝试使用this nice tutorial使用django-hstore。我在South管理的现有应用中添加了两个类:

class Attribute(models.Model):
    name  = models.CharField(max_length=200, verbose_name=_("name"))
    description = models.CharField(max_length=1000, verbose_name=_("description"))

class Measure(models.Model):
    attribute = models.ForeignKey(Attribute)
    data = hstore.DictionaryField(db_index=True)
    objects = hstore.HStoreManager()

做了一个schemamigration --auto,发起了迁移并获得了django.db.utils.DatabaseError: type "hstore" does not exist

好吧,tuto似乎不完整,django-hstore documentation告诉我使用自定义数据库后端,我将以下内容添加到我的设置文件中:

DATABASES['default']['ENGINE'] = 'django_hstore.postgresql_psycopg2'

然后我在KeyError: 'default'得到了一个south/db/__init__.py", line 78。此时,intertubes +一些试验/错误将我指向SOUTH_DATABASE_ADAPTERS设置变量,我在设置中添加了以下内容:

SOUTH_DATABASE_ADAPTERS = {'default': 'south.db.postgresql_psycopg2'}

新错误:

File ".../psycopg2/extras.py", line 769, in register_hstore
"hstore type not found in the database. "
psycopg2.ProgrammingError: hstore type not found in the database. please install it from your 'contrib/hstore.sql' file

现在这很奇怪,因为我安装了hstore扩展:

$ sudo -u postgres psql
create extension hstore;
postgres=# CREATE EXTENSION hstore;
ERROR:  extension "hstore" already exists
postgres=# \dx
                           List of installed extensions
  Name   | Version |   Schema   |                   Description                    
---------+---------+------------+--------------------------------------------------
 hstore  | 1.0     | public     | data type for storing sets of (key, value) pairs
 plpgsql | 1.0     | pg_catalog | PL/pgSQL procedural language
(2 rows)
postgres=# SELECT 'hstore'::regtype::oid;
  oid  
-------
 57704
(1 row)

这应该怎么样?我正在使用Django 1.4,Postgresql 9.1。

python django psycopg2 hstore
3个回答
20
投票

我最终发现没有为我使用的特定数据库安装hstore扩展:

$ psql -d mydb
psql (9.1.4)
Type "help" for help.

mydb=# SELECT t.oid, typarray FROM pg_type t JOIN pg_namespace ns ON typnamespace = ns.oid WHERE typname = 'hstore';
 oid | typarray 
-----+----------
(0 rows)

mydb=# \dx
                 List of installed extensions
  Name   | Version |   Schema   |         Description          
---------+---------+------------+------------------------------
 plpgsql | 1.0     | pg_catalog | PL/pgSQL procedural language
(1 row)

mydb=# create extension hstore;
WARNING:  => is deprecated as an operator name
DETAIL:  This name may be disallowed altogether in future versions of PostgreSQL.
CREATE EXTENSION
mydb=# \dx
                           List of installed extensions
  Name   | Version |   Schema   |                   Description                    
---------+---------+------------+--------------------------------------------------
 hstore  | 1.0     | public     | data type for storing sets of (key, value) pairs
 plpgsql | 1.0     | pg_catalog | PL/pgSQL procedural language
(2 rows)

mydb=# SELECT t.oid, typarray FROM pg_type t JOIN pg_namespace ns ON typnamespace = ns.oid WHERE typname = 'hstore';
  oid  | typarray 
-------+----------
 58800 |    58805
(1 row)

我认为在hstore安装之后创建的数据库将包含扩展名。似乎并非如此,am I misinterpreting how extensions work ? Are they database-specific ?


4
投票

自从我上次回答以来,Django弃用并删除了pre_syncdb信号。我已经更新了答案以适应更新版本。对于较新版本,基本机制是相同的,因为两种方法都依赖于信号和仅在HSTORE扩展不存在时才执行的SQL代码。

Django 1.8+

由于Django引入了DB迁移,pre_syncdb信号是marked deprecated in 1.7completely removed in 1.9。然而,他们引入了一种名为pre_migrate的新信号,它可以以相同的方式使用。

例:

"""
This is an example models.py which contains all model definition.
"""
from django.db import connection, models
from django.db.models.signals import pre_migrate
from django.dispatch import receiver
import sys

# sender is optional but will be called for every pre_migrate signal if removed
@receiver(pre_migrate, sender=sys.modules[__name__])
def setup_postgres_hstore(sender, **kwargs):
    """
    Always create PostgreSQL HSTORE extension if it doesn't already exist
    on the database before syncing the database.
    Requires PostgreSQL 9.1 or newer.
    """
    cursor = connection.cursor()
    cursor.execute("CREATE EXTENSION IF NOT EXISTS hstore")

# ...rest of your model definition goes here
class Foo(models.Model):
    # ...field definitions, etc.

Django 1.6+ (original answer)

确保在./manage.py syncdb期间安装HSTORE扩展的一种方法是在Django 1.6引入的pre_syncdb文件中使用models.py信号。

例:

"""
This is an example models.py which contains all model definition.
"""
from django.db import connection, models
from django.db.models.signals import pre_syncdb
from django.dispatch import receiver
import sys

# sender is optional but will be called for every pre_syncdb signal if removed
@receiver(pre_syncdb, sender=sys.modules[__name__])
def setup_postgres_hstore(sender, **kwargs):
    """
    Always create PostgreSQL HSTORE extension if it doesn't already exist
    on the database before syncing the database.
    Requires PostgreSQL 9.1 or newer.
    """
    cursor = connection.cursor()
    cursor.execute("CREATE EXTENSION IF NOT EXISTS hstore")

# ...rest of your model definition goes here
class Foo(models.Model):
    # ...field definitions, etc.

我发现如果你不想为每个新的数据库实例运行它,这很有用。此方法也适用于测试数据库设置期间的Django单元测试。

关于Django中信号挂钩的更多信息:https://docs.djangoproject.com/en/1.6/ref/signals/#management-signals


1
投票

Django现在包括a migration operation to create the hstore extension in PostgreSQL

from django.contrib.postgres.operations import HStoreExtension

class Migration(migrations.Migration):
    ...

    operations = [
        HStoreExtension(),
        ...
    ]
© www.soinside.com 2019 - 2024. All rights reserved.