python - How can I define a constraint on an inherited column in SQLAlchemy? -


i have class inheritance scheme layed out in http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#joined-table-inheritance , i'd define constraint uses columns both parent , child classes.

from sqlalchemy import (     create_engine, column, integer, string, foreignkey, checkconstraint ) sqlalchemy.ext.declarative import declarative_base   base = declarative_base()   class parent(base):     __tablename__ = 'parent'      id = column(integer, primary_key=true)     type = column(string)     name = column(string)      __mapper_args__ = {'polymorphic_on': type}   class child(parent):     __tablename__ = 'child'      id = column(integer, foreignkey('parent.id'), primary_key=true)     child_name = column(string)      __mapper_args__ = {'polymorphic_identity': 'child'}     __table_args__ = (checkconstraint('name != child_name'),)   engine = create_engine(...) base.metadata.create_all(engine) 

this doesn't work because name isn't column in child; error

sqlalchemy.exc.programmingerror: (psycopg2.programmingerror) column "name" not exist  [sql: '\ncreate table child (\n\tid integer not null, \n\tprimary key (id), \n\tcheck (name="something"), \n\tforeign key(id) references parent (id)\n)\n\n'] 

so how can define such constraint?

simple answer: you cannot using check constraint.

you cannot in plain rdbms, therefore cannot in using sqlalchemy.
however, if data modifications passing through application (and not direct db access), can add validation routines classes:

class child(parent):     # ...      @validates('child_name')     def validate_child_name(self, key, child_name):         assert child_name != name         return child_name 

read more simple validators.


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -