title: Conditional backref in SQL alchemy (take field from either grandparent or parent)
body: <p>Let's say I have the following relationships:</p>
  <p><code>GrandParent</code> with <code>id</code></p>
  <p><code>Parent</code> with <code>grand_parent_id</code></p>
  <p><code>Child</code> with <code>grand_parent_id</code> and <code>parent_id</code></p>
  <p>I want the <code>Child</code> to inherit the <code>grand_parent_id</code> from either <code>Parent</code> or <code>GrandParent</code>, depending on how it's created.</p>
  <p>When I try to run the following:</p>
  <pre><code>session.add(
      GrandParent(
          Parent(
               Child()
          )
      )
  )
  </code></pre>
  <p>GrandParent will receive id <code>1</code>, Parent will get <code>grand_parent_id=1</code>, but the child will receive <code>grand_parent_id=None</code>, even though it does receive the correct <code>parent_id=1</code>. Currently, for the Child, the backref (back_populates) is set to <code>grand_parents.id</code> column.</p>
  <p>How could I have the Child inherit the grandparent id? What should my ORM models look like?
  Or should I just change the design entirely?</p>
  <p>Currently the constraint that is forcing me to have this is that the <code>Child</code> can be created with either both <code>GrandParent</code> and <code>Parent</code> or just the <code>GrandParent</code>. <code>GrandParent</code> can also be a <code>Parent</code>, so maybe there's a different way to describe this type of relationship.</p>
  <p>Any ideas are welcome!</p>