2
我想在下一個方法在Flask-SQLAlchemy的父類中添加一個唯一約束。正如你所看到的,繼承是以連接表格的方式呈現的。在父類中的UniqueConstraint SQLAlchemy
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'
任何解決方案?我的代碼有什麼問題嗎?
獨特=真正的是對單個列,我需要創建一個獨特的複方約束。 name = name是傳遞參數的顯式方式。 – Hamlett
@Jp_uy這有幫助嗎? http://stackoverflow.com/questions/10059345/sqlalchemy-unique-across-multiple-columns - 它看起來像你唯一的約束是正確的,是否修復'__init__'方法解決問題? – NuclearPeon
這幾乎是我想要做的,事實上,我正在做的事情,但與我有繼承的小差異。繼承是在我的情況下是複雜的。更具體地說,類Parametric是Bar的父類。我想在Parent中設置唯一的約束,但是當解釋器讀取孩子時,它會嘗試從孩子(我的意思是,只取出孩子屬性)創建並且失敗。 – Hamlett