~ubuntu-branches/debian/jessie/sqlalchemy/jessie

« back to all changes in this revision

Viewing changes to doc/orm/relationships.html

  • Committer: Package Import Robot
  • Author(s): Piotr Ożarowski, Jakub Wilk, Piotr Ożarowski
  • Date: 2013-07-06 20:53:52 UTC
  • mfrom: (1.4.23) (16.1.17 experimental)
  • Revision ID: package-import@ubuntu.com-20130706205352-ryppl1eto3illd79
Tags: 0.8.2-1
[ Jakub Wilk ]
* Use canonical URIs for Vcs-* fields.

[ Piotr Ożarowski ]
* New upstream release
* Upload to unstable
* Build depend on python3-all instead of -dev, extensions are not built for
  Python 3.X 

Show diffs side-by-side

added added

removed removed

Lines of Context:
10
10
    
11
11
                Relationship Configuration
12
12
             — 
13
 
    SQLAlchemy 0.7 Documentation
 
13
    SQLAlchemy 0.8 Documentation
14
14
 
15
15
        </title>
16
16
        
20
20
    <script type="text/javascript">
21
21
      var DOCUMENTATION_OPTIONS = {
22
22
          URL_ROOT:    '../',
23
 
          VERSION:     '0.7.9',
 
23
          VERSION:     '0.8.2',
24
24
          COLLAPSE_MODINDEX: false,
25
25
          FILE_SUFFIX: '.html'
26
26
      };
32
32
    <link rel="index" title="Index" href="../genindex.html" />
33
33
    <link rel="search" title="Search" href="../search.html" />
34
34
        <link rel="copyright" title="Copyright" href="../copyright.html" />
35
 
    <link rel="top" title="SQLAlchemy 0.7 Documentation" href="../index.html" />
 
35
    <link rel="top" title="SQLAlchemy 0.8 Documentation" href="../index.html" />
36
36
        <link rel="up" title="SQLAlchemy ORM" href="index.html" />
37
37
        <link rel="next" title="Collection Configuration and Techniques" href="collections.html" />
38
38
        <link rel="prev" title="Mapper Configuration" href="mapper_config.html" />
55
55
 
56
56
 
57
57
<div id="docs-header">
58
 
    <h1>SQLAlchemy 0.7 Documentation</h1>
 
58
    <h1>SQLAlchemy 0.8 Documentation</h1>
59
59
 
60
60
    <div id="docs-search">
61
61
    Search:
67
67
    </div>
68
68
 
69
69
    <div id="docs-version-header">
70
 
        Release: <span class="version-num">0.7.9</span> | Release Date: October 1, 2012
 
70
        Release: <span class="version-num">0.8.2</span> | Release Date: July 3, 2013
71
71
 
72
72
 
73
73
    </div>
93
93
    </div>
94
94
 
95
95
    <div id="docs-navigation-banner">
96
 
        <a href="../index.html">SQLAlchemy 0.7 Documentation</a>
 
96
        <a href="../index.html">SQLAlchemy 0.8 Documentation</a>
97
97
                » <a href="index.html" title="SQLAlchemy ORM">SQLAlchemy ORM</a>
98
98
        » 
99
99
                Relationship Configuration
126
126
</ul>
127
127
</li>
128
128
<li><a class="reference internal" href="#adjacency-list-relationships">Adjacency List Relationships</a><ul>
 
129
<li><a class="reference internal" href="#composite-adjacency-lists">Composite Adjacency Lists</a></li>
129
130
<li><a class="reference internal" href="#self-referential-query-strategies">Self-Referential Query Strategies</a></li>
130
131
<li><a class="reference internal" href="#configuring-self-referential-eager-loading">Configuring Self-Referential Eager Loading</a></li>
131
132
</ul>
135
136
<li><a class="reference internal" href="#one-way-backrefs">One Way Backrefs</a></li>
136
137
</ul>
137
138
</li>
138
 
<li><a class="reference internal" href="#setting-the-primaryjoin-and-secondaryjoin">Setting the primaryjoin and secondaryjoin</a><ul>
 
139
<li><a class="reference internal" href="#configuring-how-relationship-joins">Configuring how Relationship Joins</a><ul>
 
140
<li><a class="reference internal" href="#handling-multiple-join-paths">Handling Multiple Join Paths</a></li>
139
141
<li><a class="reference internal" href="#specifying-alternate-join-conditions">Specifying Alternate Join Conditions</a></li>
 
142
<li><a class="reference internal" href="#creating-custom-foreign-conditions">Creating Custom Foreign Conditions</a></li>
140
143
<li><a class="reference internal" href="#self-referential-many-to-many-relationship">Self-Referential Many-to-Many Relationship</a></li>
141
 
<li><a class="reference internal" href="#specifying-foreign-keys">Specifying Foreign Keys</a></li>
142
144
<li><a class="reference internal" href="#building-query-enabled-properties">Building Query-Enabled Properties</a></li>
143
145
</ul>
144
146
</li>
368
370
&#8220;secondary&#8221; table as referencing rows in &#8220;child&#8221; are deleted.   SQLAlchemy
369
371
can be instructed to forego actively loading in the <tt class="docutils literal"><span class="pre">Child.parents</span></tt>
370
372
collection in this case using the <tt class="docutils literal"><span class="pre">passive_deletes=True</span></tt> directive
371
 
on <tt class="xref py py-meth docutils literal"><span class="pre">relationship()</span></tt>; see <a class="reference internal" href="collections.html#passive-deletes"><em>Using Passive Deletes</em></a> for more details
 
373
on <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>; see <a class="reference internal" href="collections.html#passive-deletes"><em>Using Passive Deletes</em></a> for more details
372
374
on this.</li>
373
375
</ul>
374
376
<p>Note again, these behaviors are <em>only</em> relevant to the <tt class="docutils literal"><span class="pre">secondary</span></tt> option
461
463
</div>
462
464
</div>
463
465
<div class="section" id="adjacency-list-relationships">
464
 
<h2>Adjacency List Relationships<a class="headerlink" href="#adjacency-list-relationships" title="Permalink to this headline">¶</a></h2>
 
466
<span id="self-referential"></span><h2>Adjacency List Relationships<a class="headerlink" href="#adjacency-list-relationships" title="Permalink to this headline">¶</a></h2>
465
467
<p>The <strong>adjacency list</strong> pattern is a common relational pattern whereby a table
466
468
contains a foreign key reference to itself. This is the most common
467
469
way to represent hierarchical data in flat tables.  Other methods
530
532
<p>There are several examples included with SQLAlchemy illustrating
531
533
self-referential strategies; these include <a class="reference internal" href="examples.html#examples-adjacencylist"><em>Adjacency List</em></a> and
532
534
<a class="reference internal" href="examples.html#examples-xmlpersistence"><em>XML Persistence</em></a>.</p>
 
535
<div class="section" id="composite-adjacency-lists">
 
536
<h3>Composite Adjacency Lists<a class="headerlink" href="#composite-adjacency-lists" title="Permalink to this headline">¶</a></h3>
 
537
<p>A sub-category of the adjacency list relationship is the rare
 
538
case where a particular column is present on both the &#8220;local&#8221; and
 
539
&#8220;remote&#8221; side of the join condition.  An example is the <tt class="docutils literal"><span class="pre">Folder</span></tt>
 
540
class below; using a composite primary key, the <tt class="docutils literal"><span class="pre">account_id</span></tt>
 
541
column refers to itself, to indicate sub folders which are within
 
542
the same account as that of the parent; while <tt class="docutils literal"><span class="pre">folder_id</span></tt> refers
 
543
to a specific folder within that account:</p>
 
544
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Folder</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
 
545
    <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">&#39;folder&#39;</span>
 
546
    <span class="n">__table_args__</span> <span class="o">=</span> <span class="p">(</span>
 
547
      <span class="n">ForeignKeyConstraint</span><span class="p">(</span>
 
548
          <span class="p">[</span><span class="s">&#39;account_id&#39;</span><span class="p">,</span> <span class="s">&#39;parent_id&#39;</span><span class="p">],</span>
 
549
          <span class="p">[</span><span class="s">&#39;folder.account_id&#39;</span><span class="p">,</span> <span class="s">&#39;folder.folder_id&#39;</span><span class="p">]),</span>
 
550
    <span class="p">)</span>
 
551
 
 
552
    <span class="n">account_id</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">Integer</span><span class="p">,</span> <span class="n">primary_key</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
 
553
    <span class="n">folder_id</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">Integer</span><span class="p">,</span> <span class="n">primary_key</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
 
554
    <span class="n">parent_id</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">Integer</span><span class="p">)</span>
 
555
    <span class="n">name</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">String</span><span class="p">)</span>
 
556
 
 
557
    <span class="n">parent_folder</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">&quot;Folder&quot;</span><span class="p">,</span>
 
558
                        <span class="n">backref</span><span class="o">=</span><span class="s">&quot;child_folders&quot;</span><span class="p">,</span>
 
559
                        <span class="n">remote_side</span><span class="o">=</span><span class="p">[</span><span class="n">account_id</span><span class="p">,</span> <span class="n">folder_id</span><span class="p">]</span>
 
560
                  <span class="p">)</span></pre></div>
 
561
</div>
 
562
<p>Above, we pass <tt class="docutils literal"><span class="pre">account_id</span></tt> into the <tt class="docutils literal"><span class="pre">remote_side</span></tt> list.
 
563
<a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> recognizes that the <tt class="docutils literal"><span class="pre">account_id</span></tt> column here
 
564
is on both sides, and aligns the &#8220;remote&#8221; column along with the
 
565
<tt class="docutils literal"><span class="pre">folder_id</span></tt> column, which it recognizes as uniquely present on
 
566
the &#8220;remote&#8221; side.</p>
 
567
<p class="versionadded">
 
568
<span class="versionmodified">New in version 0.8: </span>Support for self-referential composite keys in <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>
 
569
where a column points to itself.</p>
 
570
</div>
533
571
<div class="section" id="self-referential-query-strategies">
534
572
<h3>Self-Referential Query Strategies<a class="headerlink" href="#self-referential-query-strategies" title="Permalink to this headline">¶</a></h3>
535
573
<p>Querying of self-referential structures works like any other query:</p>
541
579
a join from a table to itself requires that at least one side of the
542
580
expression be &#8220;aliased&#8221; so that it can be unambiguously referred to.</p>
543
581
<p>Recall from <a class="reference internal" href="tutorial.html#ormtutorial-aliases"><em>Using Aliases</em></a> in the ORM tutorial that the
544
 
<a class="reference internal" href="query.html#sqlalchemy.orm.aliased" title="sqlalchemy.orm.aliased"><tt class="xref py py-class docutils literal"><span class="pre">orm.aliased</span></tt></a> construct is normally used to provide an &#8220;alias&#8221; of
 
582
<a class="reference internal" href="query.html#sqlalchemy.orm.aliased" title="sqlalchemy.orm.aliased"><tt class="xref py py-func docutils literal"><span class="pre">orm.aliased()</span></tt></a> construct is normally used to provide an &#8220;alias&#8221; of
545
583
an ORM entity.  Joining from <tt class="docutils literal"><span class="pre">Node</span></tt> to itself using this technique
546
584
looks like:</p>
547
585
<div class="highlight-python+sql"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">aliased</span>
757
795
direction.  The usual case
758
796
here is a many-to-many <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> that has a <tt class="docutils literal"><span class="pre">secondary</span></tt> argument,
759
797
or a one-to-many or many-to-one which has a <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> argument (the
760
 
<tt class="docutils literal"><span class="pre">primaryjoin</span></tt> argument is discussed in <a class="reference internal" href="#relationship-primaryjoin"><em>Setting the primaryjoin and secondaryjoin</em></a>).  Such
 
798
<tt class="docutils literal"><span class="pre">primaryjoin</span></tt> argument is discussed in <a class="reference internal" href="#relationship-primaryjoin"><em>Specifying Alternate Join Conditions</em></a>).  Such
761
799
as if we limited the list of <tt class="docutils literal"><span class="pre">Address</span></tt> objects to those which start with &#8220;tony&#8221;:</p>
762
800
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">Integer</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">,</span> <span class="n">String</span><span class="p">,</span> <span class="n">Column</span>
763
801
<span class="kn">from</span> <span class="nn">sqlalchemy.ext.declarative</span> <span class="kn">import</span> <span class="n">declarative_base</span>
892
930
these to a minimum overall.</p>
893
931
</div>
894
932
</div>
895
 
<div class="section" id="setting-the-primaryjoin-and-secondaryjoin">
896
 
<span id="relationship-primaryjoin"></span><h2>Setting the primaryjoin and secondaryjoin<a class="headerlink" href="#setting-the-primaryjoin-and-secondaryjoin" title="Permalink to this headline">¶</a></h2>
897
 
<p>A common scenario arises when we attempt to relate two
898
 
classes together, where there exist multiple ways to join the
899
 
two tables.</p>
 
933
<div class="section" id="configuring-how-relationship-joins">
 
934
<span id="relationship-configure-joins"></span><h2>Configuring how Relationship Joins<a class="headerlink" href="#configuring-how-relationship-joins" title="Permalink to this headline">¶</a></h2>
 
935
<p><a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> will normally create a join between two tables
 
936
by examining the foreign key relationship between the two tables
 
937
to determine which columns should be compared.  There are a variety
 
938
of situations where this behavior needs to be customized.</p>
 
939
<div class="section" id="handling-multiple-join-paths">
 
940
<span id="relationship-foreign-keys"></span><h3>Handling Multiple Join Paths<a class="headerlink" href="#handling-multiple-join-paths" title="Permalink to this headline">¶</a></h3>
 
941
<p>One of the most common situations to deal with is when
 
942
there are more than one foreign key path between two tables.</p>
900
943
<p>Consider a <tt class="docutils literal"><span class="pre">Customer</span></tt> class that contains two foreign keys to an <tt class="docutils literal"><span class="pre">Address</span></tt>
901
944
class:</p>
902
945
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">Integer</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">,</span> <span class="n">String</span><span class="p">,</span> <span class="n">Column</span>
925
968
    <span class="nb">zip</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">String</span><span class="p">)</span></pre></div>
926
969
</div>
927
970
<p>The above mapping, when we attempt to use it, will produce the error:</p>
928
 
<div class="highlight-python"><pre>sqlalchemy.exc.ArgumentError: Could not determine join condition between
929
 
parent/child tables on relationship Customer.billing_address. Specify a
930
 
'primaryjoin' expression. If 'secondary' is present, 'secondaryjoin' is
931
 
needed as well.</pre>
 
971
<div class="highlight-python"><pre>sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join
 
972
condition between parent/child tables on relationship
 
973
Customer.billing_address - there are multiple foreign key
 
974
paths linking the tables.  Specify the 'foreign_keys' argument,
 
975
providing a list of those columns which should be
 
976
counted as containing a foreign key reference to the parent table.</pre>
932
977
</div>
933
 
<p>What this error means is that if you have a <tt class="docutils literal"><span class="pre">Customer</span></tt> object, and wish
934
 
to load in an associated <tt class="docutils literal"><span class="pre">Address</span></tt>, there is the choice of retrieving
935
 
the <tt class="docutils literal"><span class="pre">Address</span></tt> referred to by the <tt class="docutils literal"><span class="pre">billing_address_id</span></tt> column or the one
936
 
referred to by the <tt class="docutils literal"><span class="pre">shipping_address_id</span></tt> column.  The <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>,
937
 
as it is, cannot determine its full configuration.   The examples at
938
 
<a class="reference internal" href="#relationship-patterns"><em>Basic Relational Patterns</em></a> didn&#8217;t have this issue, because in each of those examples
939
 
there was only <strong>one</strong> way to refer to the related table.</p>
940
 
<p>To resolve this issue, <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> accepts an argument named
941
 
<tt class="docutils literal"><span class="pre">primaryjoin</span></tt> which accepts a Python-based SQL expression, using the system described
942
 
at <a class="reference internal" href="../core/tutorial.html"><em>SQL Expression Language Tutorial</em></a>, that describes how the two tables should be joined
943
 
together.  When using the declarative system, we often will specify this Python
944
 
expression within a string, which is late-evaluated by the mapping configuration
945
 
system so that it has access to the full namespace of available classes:</p>
 
978
<p>The above message is pretty long.  There are many potential messages
 
979
that <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> can return, which have been carefully tailored
 
980
to detect a variety of common configurational issues; most will suggest
 
981
the additional configuration that&#8217;s needed to resolve the ambiguity
 
982
or other missing information.</p>
 
983
<p>In this case, the message wants us to qualify each <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>
 
984
by instructing for each one which foreign key column should be considered, and
 
985
the appropriate form is as follows:</p>
946
986
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Customer</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
947
987
    <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">&#39;customer&#39;</span>
948
988
    <span class="nb">id</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">Integer</span><span class="p">,</span> <span class="n">primary_key</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
951
991
    <span class="n">billing_address_id</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">Integer</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s">&quot;address.id&quot;</span><span class="p">))</span>
952
992
    <span class="n">shipping_address_id</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">Integer</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s">&quot;address.id&quot;</span><span class="p">))</span>
953
993
 
954
 
    <span class="n">billing_address</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">&quot;Address&quot;</span><span class="p">,</span>
955
 
                    <span class="n">primaryjoin</span><span class="o">=</span><span class="s">&quot;Address.id==Customer.billing_address_id&quot;</span><span class="p">)</span>
956
 
    <span class="n">shipping_address</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">&quot;Address&quot;</span><span class="p">,</span>
957
 
                    <span class="n">primaryjoin</span><span class="o">=</span><span class="s">&quot;Address.id==Customer.shipping_address_id&quot;</span><span class="p">)</span></pre></div>
 
994
    <span class="n">billing_address</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">&quot;Address&quot;</span><span class="p">,</span> <span class="n">foreign_keys</span><span class="o">=</span><span class="p">[</span><span class="n">billing_address_id</span><span class="p">])</span>
 
995
    <span class="n">shipping_address</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">&quot;Address&quot;</span><span class="p">,</span> <span class="n">foreign_keys</span><span class="o">=</span><span class="p">[</span><span class="n">shipping_address_id</span><span class="p">])</span></pre></div>
958
996
</div>
959
 
<p>Above, loading the <tt class="docutils literal"><span class="pre">Customer.billing_address</span></tt> relationship from a <tt class="docutils literal"><span class="pre">Customer</span></tt>
 
997
<p>Above, we specify the <tt class="docutils literal"><span class="pre">foreign_keys</span></tt> argument, which is a <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> or list
 
998
of <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> objects which indicate those columns to be considered &#8220;foreign&#8221;,
 
999
or in other words, the columns that contain a value referring to a parent table.
 
1000
Loading the <tt class="docutils literal"><span class="pre">Customer.billing_address</span></tt> relationship from a <tt class="docutils literal"><span class="pre">Customer</span></tt>
960
1001
object will use the value present in <tt class="docutils literal"><span class="pre">billing_address_id</span></tt> in order to
961
1002
identify the row in <tt class="docutils literal"><span class="pre">Address</span></tt> to be loaded; similarly, <tt class="docutils literal"><span class="pre">shipping_address_id</span></tt>
962
1003
is used for the <tt class="docutils literal"><span class="pre">shipping_address</span></tt> relationship.   The linkage of the two
963
1004
columns also plays a role during persistence; the newly generated primary key
964
1005
of a just-inserted <tt class="docutils literal"><span class="pre">Address</span></tt> object will be copied into the appropriate
965
1006
foreign key column of an associated <tt class="docutils literal"><span class="pre">Customer</span></tt> object during a flush.</p>
 
1007
<p>When specifying <tt class="docutils literal"><span class="pre">foreign_keys</span></tt> with Declarative, we can also use string
 
1008
names to specify, however it is important that if using a list, the <strong>list
 
1009
is part of the string</strong>:</p>
 
1010
<div class="highlight-python"><div class="highlight"><pre><span class="n">billing_address</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">&quot;Address&quot;</span><span class="p">,</span> <span class="n">foreign_keys</span><span class="o">=</span><span class="s">&quot;[Customer.billing_address_id]&quot;</span><span class="p">)</span></pre></div>
 
1011
</div>
 
1012
<p>In this specific example, the list is not necessary in any case as there&#8217;s only
 
1013
one <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> we need:</p>
 
1014
<div class="highlight-python"><div class="highlight"><pre><span class="n">billing_address</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">&quot;Address&quot;</span><span class="p">,</span> <span class="n">foreign_keys</span><span class="o">=</span><span class="s">&quot;Customer.billing_address_id&quot;</span><span class="p">)</span></pre></div>
 
1015
</div>
 
1016
<p class="versionchanged">
 
1017
<span class="versionmodified">Changed in version 0.8: </span><a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> can resolve ambiguity between foreign key targets on the
 
1018
basis of the <tt class="docutils literal"><span class="pre">foreign_keys</span></tt> argument alone; the <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> argument is no
 
1019
longer needed in this situation.</p>
 
1020
</div>
966
1021
<div class="section" id="specifying-alternate-join-conditions">
967
 
<h3>Specifying Alternate Join Conditions<a class="headerlink" href="#specifying-alternate-join-conditions" title="Permalink to this headline">¶</a></h3>
968
 
<p>The open-ended nature of <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> also allows us to customize how
969
 
related items are loaded.   In the example below, using the <tt class="docutils literal"><span class="pre">User</span></tt> class
 
1022
<span id="relationship-primaryjoin"></span><h3>Specifying Alternate Join Conditions<a class="headerlink" href="#specifying-alternate-join-conditions" title="Permalink to this headline">¶</a></h3>
 
1023
<p>The default behavior of <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> when constructing a join
 
1024
is that it equates the value of primary key columns
 
1025
on one side to that of foreign-key-referring columns on the other.
 
1026
We can change this criterion to be anything we&#8217;d like using the <tt class="docutils literal"><span class="pre">primaryjoin</span></tt>
 
1027
argument, as well as the <tt class="docutils literal"><span class="pre">secondaryjoin</span></tt> argument in the case when
 
1028
a &#8220;secondary&#8221; table is used.</p>
 
1029
<p>In the example below, using the <tt class="docutils literal"><span class="pre">User</span></tt> class
970
1030
as well as an <tt class="docutils literal"><span class="pre">Address</span></tt> class which stores a street address,  we
971
1031
create a relationship <tt class="docutils literal"><span class="pre">boston_addresses</span></tt> which will only
972
1032
load those <tt class="docutils literal"><span class="pre">Address</span></tt> objects which specify a city of &#8220;Boston&#8221;:</p>
1000
1060
to just <tt class="docutils literal"><span class="pre">city='Boston'</span></tt>.   When using Declarative, rudimentary SQL functions like
1001
1061
<a class="reference internal" href="../core/expression_api.html#sqlalchemy.sql.expression.and_" title="sqlalchemy.sql.expression.and_"><tt class="xref py py-func docutils literal"><span class="pre">and_()</span></tt></a> are automatically available in the evaluated namespace of a string
1002
1062
<a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> argument.</p>
1003
 
<p>When using classical mappings, we have the advantage of the <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> objects
1004
 
already being present when the mapping is defined, so that the SQL expression
1005
 
can be created immediately:</p>
1006
 
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">relationship</span><span class="p">,</span> <span class="n">mapper</span>
1007
 
 
1008
 
<span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
1009
 
    <span class="k">pass</span>
1010
 
<span class="k">class</span> <span class="nc">Address</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
1011
 
    <span class="k">pass</span>
1012
 
 
1013
 
<span class="n">mapper</span><span class="p">(</span><span class="n">Address</span><span class="p">,</span> <span class="n">addresses_table</span><span class="p">)</span>
1014
 
<span class="n">mapper</span><span class="p">(</span><span class="n">User</span><span class="p">,</span> <span class="n">users_table</span><span class="p">,</span> <span class="n">properties</span><span class="o">=</span><span class="p">{</span>
1015
 
    <span class="s">&#39;boston_addresses&#39;</span><span class="p">:</span> <span class="n">relationship</span><span class="p">(</span><span class="n">Address</span><span class="p">,</span> <span class="n">primaryjoin</span><span class="o">=</span>
1016
 
                <span class="n">and_</span><span class="p">(</span><span class="n">users_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="o">==</span><span class="n">addresses_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">user_id</span><span class="p">,</span>
1017
 
                <span class="n">addresses_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">city</span><span class="o">==</span><span class="s">&#39;Boston&#39;</span><span class="p">))</span>
1018
 
<span class="p">})</span></pre></div>
1019
 
</div>
1020
 
<p>Note that the custom criteria we use in a <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> is generally only significant
 
1063
<p>The custom criteria we use in a <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> is generally only significant
1021
1064
when SQLAlchemy is rendering SQL in order to load or represent this relationship.
1022
1065
That is, it&#8217;s  used
1023
1066
in the SQL statement that&#8217;s emitted in order to perform a per-attribute lazy load, or when a join is
1031
1074
for each row.  The <tt class="docutils literal"><span class="pre">city</span></tt> criteria has no effect here, as the flush process only cares about synchronizing primary
1032
1075
key values into referencing foreign key values.</p>
1033
1076
</div>
 
1077
<div class="section" id="creating-custom-foreign-conditions">
 
1078
<span id="relationship-custom-foreign"></span><h3>Creating Custom Foreign Conditions<a class="headerlink" href="#creating-custom-foreign-conditions" title="Permalink to this headline">¶</a></h3>
 
1079
<p>Another element of the primary join condition is how those columns
 
1080
considered &#8220;foreign&#8221; are determined.  Usually, some subset
 
1081
of <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> objects will specify <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.ForeignKey" title="sqlalchemy.schema.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>, or otherwise
 
1082
be part of a <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.ForeignKeyConstraint" title="sqlalchemy.schema.ForeignKeyConstraint"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKeyConstraint</span></tt></a> that&#8217;s relevant to the join condition.
 
1083
<a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> looks to this foreign key status as it decides
 
1084
how it should load and persist data for this relationship.   However, the
 
1085
<tt class="docutils literal"><span class="pre">primaryjoin</span></tt> argument can be used to create a join condition that
 
1086
doesn&#8217;t involve any &#8220;schema&#8221; level foreign keys.  We can combine <tt class="docutils literal"><span class="pre">primaryjoin</span></tt>
 
1087
along with <tt class="docutils literal"><span class="pre">foreign_keys</span></tt> and <tt class="docutils literal"><span class="pre">remote_side</span></tt> explicitly in order to
 
1088
establish such a join.</p>
 
1089
<p>Below, a class <tt class="docutils literal"><span class="pre">HostEntry</span></tt> joins to itself, equating the string <tt class="docutils literal"><span class="pre">content</span></tt>
 
1090
column to the <tt class="docutils literal"><span class="pre">ip_address</span></tt> column, which is a Postgresql type called <tt class="docutils literal"><span class="pre">INET</span></tt>.
 
1091
We need to use <a class="reference internal" href="../core/expression_api.html#sqlalchemy.sql.expression.cast" title="sqlalchemy.sql.expression.cast"><tt class="xref py py-func docutils literal"><span class="pre">cast()</span></tt></a> in order to cast one side of the join to the
 
1092
type of the other:</p>
 
1093
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">cast</span><span class="p">,</span> <span class="n">String</span><span class="p">,</span> <span class="n">Column</span><span class="p">,</span> <span class="n">Integer</span>
 
1094
<span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">relationship</span>
 
1095
<span class="kn">from</span> <span class="nn">sqlalchemy.dialects.postgresql</span> <span class="kn">import</span> <span class="n">INET</span>
 
1096
 
 
1097
<span class="kn">from</span> <span class="nn">sqlalchemy.ext.declarative</span> <span class="kn">import</span> <span class="n">declarative_base</span>
 
1098
 
 
1099
<span class="n">Base</span> <span class="o">=</span> <span class="n">declarative_base</span><span class="p">()</span>
 
1100
 
 
1101
<span class="k">class</span> <span class="nc">HostEntry</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
 
1102
    <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">&#39;host_entry&#39;</span>
 
1103
 
 
1104
    <span class="nb">id</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">Integer</span><span class="p">,</span> <span class="n">primary_key</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
 
1105
    <span class="n">ip_address</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">INET</span><span class="p">)</span>
 
1106
    <span class="n">content</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">String</span><span class="p">(</span><span class="mi">50</span><span class="p">))</span>
 
1107
 
 
1108
    <span class="c"># relationship() using explicit foreign_keys, remote_side</span>
 
1109
    <span class="n">parent_host</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">&quot;HostEntry&quot;</span><span class="p">,</span>
 
1110
                        <span class="n">primaryjoin</span><span class="o">=</span><span class="n">ip_address</span> <span class="o">==</span> <span class="n">cast</span><span class="p">(</span><span class="n">content</span><span class="p">,</span> <span class="n">INET</span><span class="p">),</span>
 
1111
                        <span class="n">foreign_keys</span><span class="o">=</span><span class="n">content</span><span class="p">,</span>
 
1112
                        <span class="n">remote_side</span><span class="o">=</span><span class="n">ip_address</span>
 
1113
                    <span class="p">)</span></pre></div>
 
1114
</div>
 
1115
<p>The above relationship will produce a join like:</p>
 
1116
<div class="highlight-python"><pre>SELECT host_entry.id, host_entry.ip_address, host_entry.content
 
1117
FROM host_entry JOIN host_entry AS host_entry_1
 
1118
ON host_entry_1.ip_address = CAST(host_entry.content AS INET)</pre>
 
1119
</div>
 
1120
<p>An alternative syntax to the above is to use the <a class="reference internal" href="#sqlalchemy.orm.foreign" title="sqlalchemy.orm.foreign"><tt class="xref py py-func docutils literal"><span class="pre">foreign()</span></tt></a> and
 
1121
<a class="reference internal" href="#sqlalchemy.orm.remote" title="sqlalchemy.orm.remote"><tt class="xref py py-func docutils literal"><span class="pre">remote()</span></tt></a> <a class="reference internal" href="../glossary.html#term-annotations"><em class="xref std std-term">annotations</em></a>, inline within the <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> expression.
 
1122
This syntax represents the annotations that <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> normally
 
1123
applies by itself to the join condition given the <tt class="docutils literal"><span class="pre">foreign_keys</span></tt> and
 
1124
<tt class="docutils literal"><span class="pre">remote_side</span></tt> arguments; the functions are provided in the API in the
 
1125
rare case that <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> can&#8217;t determine the exact location
 
1126
of these features on its own:</p>
 
1127
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">foreign</span><span class="p">,</span> <span class="n">remote</span>
 
1128
 
 
1129
<span class="k">class</span> <span class="nc">HostEntry</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
 
1130
    <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">&#39;host_entry&#39;</span>
 
1131
 
 
1132
    <span class="nb">id</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">Integer</span><span class="p">,</span> <span class="n">primary_key</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
 
1133
    <span class="n">ip_address</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">INET</span><span class="p">)</span>
 
1134
    <span class="n">content</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="n">String</span><span class="p">(</span><span class="mi">50</span><span class="p">))</span>
 
1135
 
 
1136
    <span class="c"># relationship() using explicit foreign() and remote() annotations</span>
 
1137
    <span class="c"># in lieu of separate arguments</span>
 
1138
    <span class="n">parent_host</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">&quot;HostEntry&quot;</span><span class="p">,</span>
 
1139
                        <span class="n">primaryjoin</span><span class="o">=</span><span class="n">remote</span><span class="p">(</span><span class="n">ip_address</span><span class="p">)</span> <span class="o">==</span> \
 
1140
                                <span class="n">cast</span><span class="p">(</span><span class="n">foreign</span><span class="p">(</span><span class="n">content</span><span class="p">),</span> <span class="n">INET</span><span class="p">),</span>
 
1141
                    <span class="p">)</span></pre></div>
 
1142
</div>
 
1143
</div>
1034
1144
<div class="section" id="self-referential-many-to-many-relationship">
1035
1145
<span id="self-referential-many-to-many"></span><h3>Self-Referential Many-to-Many Relationship<a class="headerlink" href="#self-referential-many-to-many-relationship" title="Permalink to this headline">¶</a></h3>
1036
1146
<p>Many to many relationships can be customized by one or both of <tt class="docutils literal"><span class="pre">primaryjoin</span></tt>
1097
1207
backref - when <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> creates the second relationship in the reverse
1098
1208
direction, it&#8217;s smart enough to reverse the <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> and <tt class="docutils literal"><span class="pre">secondaryjoin</span></tt> arguments.</p>
1099
1209
</div>
1100
 
<div class="section" id="specifying-foreign-keys">
1101
 
<h3>Specifying Foreign Keys<a class="headerlink" href="#specifying-foreign-keys" title="Permalink to this headline">¶</a></h3>
1102
 
<p>When using <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> and <tt class="docutils literal"><span class="pre">secondaryjoin</span></tt>, SQLAlchemy also needs to be
1103
 
aware of which columns in the relationship reference the other. In most cases,
1104
 
a <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> construct will have
1105
 
<a class="reference internal" href="../core/schema.html#sqlalchemy.schema.ForeignKey" title="sqlalchemy.schema.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a> constructs which take care of this;
1106
 
however, in the case of reflected tables on a database that does not report
1107
 
FKs (like MySQL ISAM) or when using join conditions on columns that don&#8217;t have
1108
 
foreign keys, the <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> needs to be told
1109
 
specifically which columns are &#8220;foreign&#8221; using the <tt class="docutils literal"><span class="pre">foreign_keys</span></tt>
1110
 
collection:</p>
1111
 
<div class="highlight-python+sql"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Address</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
1112
 
    <span class="n">__table__</span> <span class="o">=</span> <span class="n">addresses_table</span>
1113
 
 
1114
 
<span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
1115
 
    <span class="n">__table__</span> <span class="o">=</span> <span class="n">users_table</span>
1116
 
    <span class="n">addresses</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="n">Address</span><span class="p">,</span>
1117
 
                    <span class="n">primaryjoin</span><span class="o">=</span>
1118
 
                    <span class="n">users_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">user_id</span><span class="o">==</span><span class="n">addresses_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">user_id</span><span class="p">,</span>
1119
 
                    <span class="n">foreign_keys</span><span class="o">=</span><span class="p">[</span><span class="n">addresses_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">user_id</span><span class="p">])</span></pre></div>
1120
 
</div>
1121
 
</div>
1122
1210
<div class="section" id="building-query-enabled-properties">
1123
1211
<h3>Building Query-Enabled Properties<a class="headerlink" href="#building-query-enabled-properties" title="Permalink to this headline">¶</a></h3>
1124
1212
<p>Very ambitious custom join conditions may fail to be directly persistable, and
1352
1440
<dt id="sqlalchemy.orm.relationship">
1353
1441
<tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">relationship</tt><big>(</big><em>argument</em>, <em>secondary=None</em>, <em>**kwargs</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.relationship" title="Permalink to this definition">¶</a></dt>
1354
1442
<dd><p>Provide a relationship of a primary Mapper to a secondary Mapper.</p>
1355
 
<p class="versionchanged">
1356
 
<span class="versionmodified">Changed in version 0.6: </span><a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> is historically known as <a class="reference internal" href="#sqlalchemy.orm.relation" title="sqlalchemy.orm.relation"><tt class="xref py py-func docutils literal"><span class="pre">relation()</span></tt></a>.</p>
1357
1443
<p>This corresponds to a parent-child or associative table relationship.  The
1358
1444
constructed class is an instance of <a class="reference internal" href="internals.html#sqlalchemy.orm.properties.RelationshipProperty" title="sqlalchemy.orm.properties.RelationshipProperty"><tt class="xref py py-class docutils literal"><span class="pre">RelationshipProperty</span></tt></a>.</p>
1359
1445
<p>A typical <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>, used in a classical mapping:</p>
1363
1449
</div>
1364
1450
<p>Some arguments accepted by <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> optionally accept a
1365
1451
callable function, which when called produces the desired value.
1366
 
The callable is invoked by the parent <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> at &#8220;mapper initialization&#8221;
1367
 
time, which happens only when mappers are first used, and is assumed
1368
 
to be after all mappings have been constructed.  This can be used
1369
 
to resolve order-of-declaration and other dependency issues, such as
 
1452
The callable is invoked by the parent <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> at &#8220;mapper
 
1453
initialization&#8221; time, which happens only when mappers are first used, and
 
1454
is assumed to be after all mappings have been constructed.  This can be
 
1455
used to resolve order-of-declaration and other dependency issues, such as
1370
1456
if <tt class="docutils literal"><span class="pre">Child</span></tt> is declared below <tt class="docutils literal"><span class="pre">Parent</span></tt> in the same file:</p>
1371
1457
<div class="highlight-python"><div class="highlight"><pre><span class="n">mapper</span><span class="p">(</span><span class="n">Parent</span><span class="p">,</span> <span class="n">properties</span><span class="o">=</span><span class="p">{</span>
1372
1458
    <span class="s">&quot;children&quot;</span><span class="p">:</span><span class="n">relationship</span><span class="p">(</span><span class="k">lambda</span><span class="p">:</span> <span class="n">Child</span><span class="p">,</span>
1378
1464
These string arguments are converted into callables that evaluate
1379
1465
the string as Python code, using the Declarative
1380
1466
class-registry as a namespace.  This allows the lookup of related
1381
 
classes to be automatic via their string name, and removes the need to import
1382
 
related classes at all into the local module space:</p>
 
1467
classes to be automatic via their string name, and removes the need to
 
1468
import related classes at all into the local module space:</p>
1383
1469
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy.ext.declarative</span> <span class="kn">import</span> <span class="n">declarative_base</span>
1384
1470
 
1385
1471
<span class="n">Base</span> <span class="o">=</span> <span class="n">declarative_base</span><span class="p">()</span>
1396
1482
<col class="field-body" />
1397
1483
<tbody valign="top">
1398
1484
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
1399
 
<li><strong>argument</strong> &#8211; <p>a mapped class, or actual <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> instance, representing the target of
1400
 
the relationship.</p>
 
1485
<li><strong>argument</strong> &#8211; <p>a mapped class, or actual <a class="reference internal" href="mapper_config.html#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> instance, representing the
 
1486
target of the relationship.</p>
1401
1487
<p><tt class="docutils literal"><span class="pre">argument</span></tt> may also be passed as a callable function
1402
1488
which is evaluated at mapper initialization time, and may be passed as a
1403
1489
Python-evaluable string when using Declarative.</p>
1503
1589
which will be prepended to the list of attribute listeners for
1504
1590
the resulting descriptor placed on the class.
1505
1591
<strong>Deprecated.</strong>  Please see <a class="reference internal" href="events.html#sqlalchemy.orm.events.AttributeEvents" title="sqlalchemy.orm.events.AttributeEvents"><tt class="xref py py-class docutils literal"><span class="pre">AttributeEvents</span></tt></a>.</li>
1506
 
<li><strong>foreign_keys</strong> &#8211; <p>a list of columns which are to be used as &#8220;foreign key&#8221; columns.
1507
 
Normally, <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> uses the <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.ForeignKey" title="sqlalchemy.schema.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>
1508
 
and <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.ForeignKeyConstraint" title="sqlalchemy.schema.ForeignKeyConstraint"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKeyConstraint</span></tt></a> objects present within the
1509
 
mapped or secondary <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> to determine the &#8220;foreign&#8221; side of
1510
 
the join condition.  This is used to construct SQL clauses in order
1511
 
to load objects, as well as to &#8220;synchronize&#8221; values from
1512
 
primary key columns to referencing foreign key columns.
1513
 
The <tt class="docutils literal"><span class="pre">foreign_keys</span></tt> parameter overrides the notion of what&#8217;s
1514
 
&#8220;foreign&#8221; in the table metadata, allowing the specification
1515
 
of a list of <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> objects that should be considered
1516
 
part of the foreign key.</p>
1517
 
<p>There are only two use cases for <tt class="docutils literal"><span class="pre">foreign_keys</span></tt> - one, when it is not
1518
 
convenient for <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> metadata to contain its own foreign key
1519
 
metadata (which should be almost never, unless reflecting a large amount of
1520
 
tables from a MySQL MyISAM schema, or a schema that doesn&#8217;t actually
1521
 
have foreign keys on it). The other is for extremely
1522
 
rare and exotic composite foreign key setups where some columns
1523
 
should artificially not be considered as foreign.</p>
 
1592
<li><strong>foreign_keys</strong> &#8211; <p>a list of columns which are to be used as &#8220;foreign key&#8221; columns,
 
1593
or columns which refer to the value in a remote column, within the
 
1594
context of this <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> object&#8217;s <tt class="docutils literal"><span class="pre">primaryjoin</span></tt>
 
1595
condition.   That is, if the <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> condition of this
 
1596
<a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> is <tt class="docutils literal"><span class="pre">a.id</span> <span class="pre">==</span> <span class="pre">b.a_id</span></tt>, and the values in <tt class="docutils literal"><span class="pre">b.a_id</span></tt>
 
1597
are required to be present in <tt class="docutils literal"><span class="pre">a.id</span></tt>, then the &#8220;foreign key&#8221; column
 
1598
of this <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> is <tt class="docutils literal"><span class="pre">b.a_id</span></tt>.</p>
 
1599
<p>In normal cases, the <tt class="docutils literal"><span class="pre">foreign_keys</span></tt> parameter is <strong>not required.</strong>
 
1600
<a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> will <strong>automatically</strong> determine which columns
 
1601
in the <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> conditition are to be considered &#8220;foreign key&#8221;
 
1602
columns based on those <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> objects that specify
 
1603
<a class="reference internal" href="../core/schema.html#sqlalchemy.schema.ForeignKey" title="sqlalchemy.schema.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>, or are otherwise listed as referencing columns
 
1604
in a <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.ForeignKeyConstraint" title="sqlalchemy.schema.ForeignKeyConstraint"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKeyConstraint</span></tt></a> construct.  <tt class="docutils literal"><span class="pre">foreign_keys</span></tt> is only
 
1605
needed when:</p>
 
1606
<blockquote>
 
1607
<div><ol class="arabic">
 
1608
<li>There is more than one way to construct a join from the local
 
1609
table to the remote table, as there are multiple foreign key
 
1610
references present.  Setting <tt class="docutils literal"><span class="pre">foreign_keys</span></tt> will limit the
 
1611
<a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> to consider just those columns specified
 
1612
here as &#8220;foreign&#8221;.<p class="versionchanged">
 
1613
<span class="versionmodified">Changed in version 0.8: </span>A multiple-foreign key join ambiguity can be resolved by
 
1614
setting the <tt class="docutils literal"><span class="pre">foreign_keys</span></tt> parameter alone, without the
 
1615
need to explicitly set <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> as well.</p>
 
1616
</li>
 
1617
<li>The <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> being mapped does not actually have
 
1618
<a class="reference internal" href="../core/schema.html#sqlalchemy.schema.ForeignKey" title="sqlalchemy.schema.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a> or <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.ForeignKeyConstraint" title="sqlalchemy.schema.ForeignKeyConstraint"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKeyConstraint</span></tt></a>
 
1619
constructs present, often because the table
 
1620
was reflected from a database that does not support foreign key
 
1621
reflection (MySQL MyISAM).</li>
 
1622
<li>The <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> argument is used to construct a non-standard
 
1623
join condition, which makes use of columns or expressions that do
 
1624
not normally refer to their &#8220;parent&#8221; column, such as a join condition
 
1625
expressed by a complex comparison using a SQL function.</li>
 
1626
</ol>
 
1627
</div></blockquote>
 
1628
<p>The <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> construct will raise informative error messages
 
1629
that suggest the use of the <tt class="docutils literal"><span class="pre">foreign_keys</span></tt> parameter when presented
 
1630
with an ambiguous condition.   In typical cases, if <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>
 
1631
doesn&#8217;t raise any exceptions, the <tt class="docutils literal"><span class="pre">foreign_keys</span></tt> parameter is usually
 
1632
not needed.</p>
1524
1633
<p><tt class="docutils literal"><span class="pre">foreign_keys</span></tt> may also be passed as a callable function
1525
1634
which is evaluated at mapper initialization time, and may be passed as a
1526
1635
Python-evaluable string when using Declarative.</p>
 
1636
<div class="admonition-see-also admonition seealso">
 
1637
<p class="first admonition-title">See also</p>
 
1638
<p><a class="reference internal" href="#relationship-foreign-keys"><em>Handling Multiple Join Paths</em></a></p>
 
1639
<p><a class="reference internal" href="#relationship-custom-foreign"><em>Creating Custom Foreign Conditions</em></a></p>
 
1640
<p class="last"><a class="reference internal" href="#sqlalchemy.orm.foreign" title="sqlalchemy.orm.foreign"><tt class="xref py py-func docutils literal"><span class="pre">foreign()</span></tt></a> - allows direct annotation of the &#8220;foreign&#8221; columns
 
1641
within a <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> condition.</p>
 
1642
</div>
 
1643
<p class="versionadded">
 
1644
<span class="versionmodified">New in version 0.8: </span>The <a class="reference internal" href="#sqlalchemy.orm.foreign" title="sqlalchemy.orm.foreign"><tt class="xref py py-func docutils literal"><span class="pre">foreign()</span></tt></a> annotation can also be applied
 
1645
directly to the <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> expression, which is an alternate,
 
1646
more specific system of describing which columns in a particular
 
1647
<tt class="docutils literal"><span class="pre">primaryjoin</span></tt> should be considered &#8220;foreign&#8221;.</p>
 
1648
</li>
 
1649
<li><strong>info</strong> &#8211; <p>Optional data dictionary which will be populated into the
 
1650
<a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces.MapperProperty.info" title="sqlalchemy.orm.interfaces.MapperProperty.info"><tt class="xref py py-attr docutils literal"><span class="pre">MapperProperty.info</span></tt></a> attribute of this object.</p>
 
1651
<p class="versionadded">
 
1652
<span class="versionmodified">New in version 0.8.</span></p>
1527
1653
</li>
1528
1654
<li><strong>innerjoin=False</strong> &#8211; <p>when <tt class="docutils literal"><span class="pre">True</span></tt>, joined eager loads will use an inner join to join
1529
1655
against related tables instead of an outer join.  The purpose
1559
1685
that of the parent, using a JOIN or LEFT OUTER JOIN.  Whether
1560
1686
the join is &#8220;outer&#8221; or not is determined by the <tt class="docutils literal"><span class="pre">innerjoin</span></tt>
1561
1687
parameter.</li>
1562
 
<li><tt class="docutils literal"><span class="pre">subquery</span></tt> - items should be loaded &#8220;eagerly&#8221; within the same
1563
 
query as that of the parent, using a second SQL statement
1564
 
which issues a JOIN to a subquery of the original
1565
 
statement.</li>
 
1688
<li><tt class="docutils literal"><span class="pre">subquery</span></tt> - items should be loaded &#8220;eagerly&#8221; as the parents are
 
1689
loaded, using one additional SQL statement, which issues a JOIN to a
 
1690
subquery of the original statement, for each collection requested.</li>
1566
1691
<li><tt class="docutils literal"><span class="pre">noload</span></tt> - no loading should occur at any time.  This is to
1567
1692
support &#8220;write-only&#8221; attributes, or attributes which are
1568
1693
populated in some manner specific to the application.</li>
1578
1703
<p>Detailed discussion of loader strategies is at <a class="reference internal" href="loading.html"><em>Relationship Loading Techniques</em></a>.</p>
1579
1704
</li>
1580
1705
<li><strong>load_on_pending=False</strong> &#8211; <p>Indicates loading behavior for transient or pending parent objects.</p>
 
1706
<p class="versionchanged">
 
1707
<span class="versionmodified">Changed in version 0.8: </span>load_on_pending is superseded by
 
1708
<a class="reference internal" href="session.html#sqlalchemy.orm.session.Session.enable_relationship_loading" title="sqlalchemy.orm.session.Session.enable_relationship_loading"><tt class="xref py py-meth docutils literal"><span class="pre">Session.enable_relationship_loading()</span></tt></a>.</p>
1581
1709
<p>When set to <tt class="docutils literal"><span class="pre">True</span></tt>, causes the lazy-loader to
1582
1710
issue a query for a parent object that is not persistent, meaning it has
1583
1711
never been flushed.  This may take effect for a pending object when
1584
1712
autoflush is disabled, or for a transient object that has been
1585
1713
&#8220;attached&#8221; to a <a class="reference internal" href="session.html#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> but is not part of its pending
1586
 
collection. Attachment of transient objects to the session without
1587
 
moving to the &#8220;pending&#8221; state is not a supported behavior at this time.</p>
1588
 
<p>Note that the load of related objects on a pending or transient object
1589
 
also does not trigger any attribute change events - no user-defined
1590
 
events will be emitted for these attributes, and if and when the
1591
 
object is ultimately flushed, only the user-specific foreign key
1592
 
attributes will be part of the modified state.</p>
 
1714
collection.</p>
1593
1715
<p>The load_on_pending flag does not improve behavior
1594
1716
when the ORM is used normally - object references should be constructed
1595
1717
at the object level, not at the foreign key level, so that they
1596
1718
are present in an ordinary way before flush() proceeds.  This flag
1597
1719
is not not intended for general use.</p>
1598
 
<p>New in 0.6.5.</p>
 
1720
<p class="versionadded">
 
1721
<span class="versionmodified">New in version 0.6.5.</span></p>
1599
1722
</li>
1600
1723
<li><strong>order_by</strong> &#8211; <p>indicates the ordering that should be applied when loading these
1601
1724
items.  <tt class="docutils literal"><span class="pre">order_by</span></tt> is expected to refer to one of the <a class="reference internal" href="../core/schema.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a>
1680
1803
<p><tt class="docutils literal"><span class="pre">remote_side</span></tt> may also be passed as a callable function
1681
1804
which is evaluated at mapper initialization time, and may be passed as a
1682
1805
Python-evaluable string when using Declarative.</p>
 
1806
<p class="versionchanged">
 
1807
<span class="versionmodified">Changed in version 0.8: </span>The <a class="reference internal" href="#sqlalchemy.orm.remote" title="sqlalchemy.orm.remote"><tt class="xref py py-func docutils literal"><span class="pre">remote()</span></tt></a> annotation can also be applied
 
1808
directly to the <tt class="docutils literal"><span class="pre">primaryjoin</span></tt> expression, which is an alternate,
 
1809
more specific system of describing which columns in a particular
 
1810
<tt class="docutils literal"><span class="pre">primaryjoin</span></tt> should be considered &#8220;remote&#8221;.</p>
1683
1811
</li>
1684
1812
<li><strong>query_class</strong> &#8211; a <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query" title="sqlalchemy.orm.query.Query"><tt class="xref py py-class docutils literal"><span class="pre">Query</span></tt></a> subclass that will be used as the base of the
1685
1813
&#8220;appender query&#8221; returned by a &#8220;dynamic&#8221; relationship, that
1720
1848
</tr>
1721
1849
</tbody>
1722
1850
</table>
 
1851
<p class="versionchanged">
 
1852
<span class="versionmodified">Changed in version 0.6: </span><a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> was renamed from its previous name
 
1853
<a class="reference internal" href="#sqlalchemy.orm.relation" title="sqlalchemy.orm.relation"><tt class="xref py py-func docutils literal"><span class="pre">relation()</span></tt></a>.</p>
1723
1854
</dd></dl>
1724
1855
 
1725
1856
<dl class="function">
1726
1857
<dt id="sqlalchemy.orm.backref">
1727
1858
<tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">backref</tt><big>(</big><em>name</em>, <em>**kwargs</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.backref" title="Permalink to this definition">¶</a></dt>
1728
 
<dd><p>Create a back reference with explicit keyword arguments, which are the same
1729
 
arguments one can send to <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>.</p>
 
1859
<dd><p>Create a back reference with explicit keyword arguments, which are the
 
1860
same arguments one can send to <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>.</p>
1730
1861
<p>Used with the <tt class="docutils literal"><span class="pre">backref</span></tt> keyword argument to <a class="reference internal" href="#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a> in
1731
1862
place of a string argument, e.g.:</p>
1732
1863
<div class="highlight-python"><pre>'items':relationship(SomeItem, backref=backref('parent', lazy='subquery'))</pre>
1755
1886
on dynamic loading.</p>
1756
1887
</dd></dl>
1757
1888
 
 
1889
<dl class="function">
 
1890
<dt id="sqlalchemy.orm.foreign">
 
1891
<tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">foreign</tt><big>(</big><em>expr</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.foreign" title="Permalink to this definition">¶</a></dt>
 
1892
<dd><p>Annotate a portion of a primaryjoin expression
 
1893
with a &#8216;foreign&#8217; annotation.</p>
 
1894
<p>See the section <a class="reference internal" href="#relationship-custom-foreign"><em>Creating Custom Foreign Conditions</em></a> for a
 
1895
description of use.</p>
 
1896
<p class="versionadded">
 
1897
<span class="versionmodified">New in version 0.8.</span></p>
 
1898
<div class="admonition-see-also admonition seealso">
 
1899
<p class="first admonition-title">See also</p>
 
1900
<p><a class="reference internal" href="#relationship-custom-foreign"><em>Creating Custom Foreign Conditions</em></a></p>
 
1901
<p class="last"><a class="reference internal" href="#sqlalchemy.orm.remote" title="sqlalchemy.orm.remote"><tt class="xref py py-func docutils literal"><span class="pre">remote()</span></tt></a></p>
 
1902
</div>
 
1903
</dd></dl>
 
1904
 
 
1905
<dl class="function">
 
1906
<dt id="sqlalchemy.orm.remote">
 
1907
<tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">remote</tt><big>(</big><em>expr</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.remote" title="Permalink to this definition">¶</a></dt>
 
1908
<dd><p>Annotate a portion of a primaryjoin expression
 
1909
with a &#8216;remote&#8217; annotation.</p>
 
1910
<p>See the section <a class="reference internal" href="#relationship-custom-foreign"><em>Creating Custom Foreign Conditions</em></a> for a
 
1911
description of use.</p>
 
1912
<p class="versionadded">
 
1913
<span class="versionmodified">New in version 0.8.</span></p>
 
1914
<div class="admonition-see-also admonition seealso">
 
1915
<p class="first admonition-title">See also</p>
 
1916
<p><a class="reference internal" href="#relationship-custom-foreign"><em>Creating Custom Foreign Conditions</em></a></p>
 
1917
<p class="last"><a class="reference internal" href="#sqlalchemy.orm.foreign" title="sqlalchemy.orm.foreign"><tt class="xref py py-func docutils literal"><span class="pre">foreign()</span></tt></a></p>
 
1918
</div>
 
1919
</dd></dl>
 
1920
 
1758
1921
</div>
1759
1922
</div>
1760
1923
 
1769
1932
        <a href="collections.html" title="next chapter">Collection Configuration and Techniques</a>
1770
1933
 
1771
1934
    <div id="docs-copyright">
1772
 
        &copy; <a href="../copyright.html">Copyright</a> 2007-2012, the SQLAlchemy authors and contributors.
 
1935
        &copy; <a href="../copyright.html">Copyright</a> 2007-2013, the SQLAlchemy authors and contributors.
1773
1936
        Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3.
1774
1937
    </div>
1775
1938
</div>