Home:ALL Converter>Why does SQLAlchemy initialize hstore field as null?

Why does SQLAlchemy initialize hstore field as null?

Ask Time:2015-02-05T04:42:28         Author:erjiang

Json Formatter

I am using Flask-SQLAlchemy and have a model with the following column:

class Item(Model):
    misc = Column(MutableDict.as_mutable(postgresql.HSTORE), nullable=False,
                  server_default='',
                  default=MutableDict.as_mutable(postgresql.HSTORE))

When I try to assign fields to the model object, it seems that the misc column is None, rather than an empty dict:

my_item = Item()
my_item.misc["foo"] = "bar"
# TypeError: 'NoneType' object does not support item assignment

How can I configure the model so that new objects get initialized with an empty dictionary?

Author:erjiang,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/28331046/why-does-sqlalchemy-initialize-hstore-field-as-null
davidism :

There are two problems here. First, default should be a Python dict, not a repeat of the column type. Second, default is not used when initializing new instances, only when committing instances with no value set for that column. So you need to specifically add a default during initialization also.\n\nfrom sqlalchemy.dialects.postgresql import HSTORE\nfrom sqlalchemy.ext.mutable import MutableDict\n\nclass Item(db.Model):\n misc = db.Column(MutableDict.as_mutable(HSTORE), nullable=False, default={}, server_default='')\n\n def __init__(self, **kwargs):\n kwargs.setdefault('misc', {})\n super(Item, self).__init__(**kwargs)\n\n\n\n\nitem = Item()\nitem.misc['foo'] = 'bar'\n\n\n\n\nOn that note, there's no point in setting both default and server_default if you're only ever going to use this from Python. There's no harm either, though.\n\n\n\nI assume that you know you want an HSTORE in this specific case, but I'll also point out that PostgreSQL has the more general JSON and JSONB types now.",
2015-02-05T04:38:08
Mike Lazko :

I want to note that correct way to define default value for mutable struct \n\nmisc = db.Column(MutableDict.as_mutable(HSTORE), nullable=False, default=dict)\n\n\nit should be callable and works like factory or lambda: dict()\n\nOtherwise, it can cause unexpected effects.",
2020-04-23T08:17:39
yy