title: How can I define a constraint on an inherited column in SQLAlchemy?
body: <p>I have a class inheritance scheme as layed out in <a href="http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#joined-table-inheritance" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#joined-table-inheritance</a> and I'd like to define a constraint that uses columns from both the parent and child classes.</p>
  
  <pre><code>from sqlalchemy import (
      create_engine, Column, Integer, String, ForeignKey, CheckConstraint
  )
  from 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)
  </code></pre>
  
  <p>This doesn't work because <code>name</code> isn't a column in <code>child</code>; I get the error</p>
  
  <pre><code>sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) column "name" does 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']
  </code></pre>
  
  <p>So how can I define such a constraint?</p>