父类SQLAlchemy

时间:2015-11-11 21:38:21

标签: python flask sqlalchemy flask-sqlalchemy

我正试图在下一个方法中在Flask-SQLAlchemy的父类中添加一个唯一约束。 如您所见,继承以Joined Table方式表示。

class Parametric(object, Model):
  __tablename__ = "parametric"
  __mapper_args__ = {'polymorphic_on': type,
                     'polymorphic_identity': 'Parametric'}
  __table_args__ = (
         db.UniqueConstraint('name', 'type', name='name_type'),
     )
  id = Column(db.Integer, primary_key=True)
  name = Column(db.String(32), nullable=False)
  type = Column(db.String(50)) 

  def __init__(self, name):
   self.name = name


class Bar(Parametric):        
  __tablename__ = "bar"
  __mapper_args__ = {'polymorphic_identity': 'Foo'}
  prop = Column(db.String(32), nullable=False)
  id = db.Column(db.Integer, db.ForeignKey('parametric.id'), primary_key=True)

  def __init__(self, name, prop):
   super(Parametric, self).__init__(name=name)
   self.prop = prop

当解释器读取第一个孩子时,我会得到下一个追溯:

  File "/usr/local/lib/python2.7/dist-packages/Flask_SQLAlchemy-1.0-py2.7.egg/flask_sqlalchemy/__init__.py", line 510, in __init__
    DeclarativeMeta.__init__(self, name, bases, d)
  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/ext/declarative/api.py", line 53, in __init__
    _as_declarative(cls, classname, cls.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/ext/declarative/base.py", line 251, in _as_declarative
    **table_kw)
  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/sql/schema.py", line 352, in __new__
    table._init(name, metadata, *args, **kw)
  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/sql/schema.py", line 429, in _init
    self._init_items(*args)
  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/sql/schema.py", line 72, in _init_items
    item._set_parent_with_dispatch(self)
  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/sql/base.py", line 421, in _set_parent_with_dispatch
    self._set_parent(parent)
  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/sql/schema.py", line 2272, in _set_parent
    ColumnCollectionMixin._set_parent(self, table)
  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/sql/schema.py", line 2240, in _set_parent
    col = table.c[col]
  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/util/_collections.py", line 156, in __getitem__
    return self._data[key]
KeyError: 'name'

任何解决方案?我的代码中有什么问题吗?

1 个答案:

答案 0 :(得分:0)

在SQLAlchemy中,您可以使用UserId参数指定列是唯一的。我认为这将是一种首选的,更易读的做事方式。

我认为你的问题与继承有关,可能是语法。

在您的Parametic ForSourceMember函数中,您有unique=True。请注意__init__()是一个arg,而不是一个kwarg。而不是使用name,只需提交如下名称:

name