title: Sqlalchemy union foreign key
body: <p>I want to make table field (foreign key) that can reference to one of 2 tables: <code>Dog</code> or <code>Cat</code>.</p>
  <p>I know it may be most likely implemented in PostgreSQL (via <code>check</code>) keyword (not a part of SQL standard), not a <code>foreign key</code>).
  So I suppose it may be possible at other databases also via their private syntax.
  Theoretically it may be done by Sqlalchemy even if some particular database not supporting a such functionality.</p>
  <p>in Python code it looks like this:</p>
  <pre><code># # # SCHEMAS.PY # # #
  from dataclasses import dataclass
  
  
  @dataclass
  class Cat: ...
  
  
  @dataclass
  class Dog: ...
  
  
  @dataclass
  class review:
      stars_value: int
      entity: Cat | Dog
      comment: str
  
  # # # MODELS.PY # # #
  from sqlalchemy import Column, Table, ForeignKey, Integer, String
  from sqlalchemy.ext.declarative import declarative_base
  
  
  Base = declarative_base()
  
  
  cats = Table(
      &quot;cats&quot;,
      Base.metadata,
      Column(&quot;id&quot;, Integer, primary_key=True),
      Column(&quot;name&quot;, String)
      )
  
  dogs = Table(
      &quot;dogs&quot;,
      Base.metadata,
      Column(&quot;id&quot;, Integer, primary_key=True),
      Column(&quot;name&quot;, String),
      )
  
  review = Table(
      &quot;review&quot;,
      Base.metadata,
      Column(&quot;id&quot;, Integer, primary_key=True),
      Column(&quot;comment&quot;, String),
      Column(&quot;entity&quot;, Integer, ForeignKey(&quot;cats.id&quot; | &quot;dogs.id&quot;)  # Invalid syntax here!
      )
  </code></pre>
  <p>If no - I will do it via some intermediate table as:</p>
  <pre><code>review_categories = Table(
      &quot;review_categories&quot;,
      Base.metadata,
      Column(&quot;id&quot;, Integer, primary_key=True),
      Column(&quot;cat&quot;, Integer),
      Column(&quot;dog Integer),
  )
  </code></pre>