<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> Mapper Configuration — SQLAlchemy 0.8 Documentation </title> <!-- begin iterate through SQLA + sphinx environment css_files --> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../_static/docs.css" type="text/css" /> <link rel="stylesheet" href="../_static/changelog.css" type="text/css" /> <link rel="stylesheet" href="../_static/sphinx_paramlinks.css" type="text/css" /> <!-- end iterate through SQLA + sphinx environment css_files --> <!-- begin layout.mako headers --> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '0.8.7', COLLAPSE_MODINDEX: false, FILE_SUFFIX: '.html' }; </script> <!-- begin iterate through sphinx environment script_files --> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <!-- end iterate through sphinx environment script_files --> <script type="text/javascript" src="../_static/detectmobile.js"></script> <script type="text/javascript" src="../_static/init.js"></script> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="top" title="SQLAlchemy 0.8 Documentation" href="../index.html" /> <link rel="up" title="SQLAlchemy ORM" href="index.html" /> <link rel="next" title="Relationship Configuration" href="relationships.html" /> <link rel="prev" title="Object Relational Tutorial" href="tutorial.html" /> <!-- end layout.mako headers --> </head> <body> <div id="docs-container"> <div id="docs-top-navigation-container" class="body-background"> <div id="docs-header"> <div id="docs-version-header"> Release: <span class="version-num">0.8.7</span> | Release Date: July 22, 2014 </div> <h1>SQLAlchemy 0.8 Documentation</h1> </div> </div> <div id="docs-body-container"> <div id="fixed-sidebar" class="withsidebar"> <div id="docs-sidebar-popout"> <h3><a href="../index.html">SQLAlchemy 0.8 Documentation</a></h3> <p id="sidebar-paginate"> <a href="index.html" title="SQLAlchemy ORM">Up</a> | <a href="tutorial.html" title="Object Relational Tutorial">Prev</a> | <a href="relationships.html" title="Relationship Configuration">Next</a> </p> <p id="sidebar-topnav"> <a href="../index.html">Contents</a> | <a href="../genindex.html">Index</a> </p> <div id="sidebar-search"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" size="12" /> <input type="submit" value="Search" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div id="docs-sidebar"> <h3><a href="#"> Mapper Configuration </a></h3> <ul> <li><a class="reference internal" href="#">Mapper Configuration</a><ul> <li><a class="reference internal" href="#classical-mappings">Classical Mappings</a></li> <li><a class="reference internal" href="#customizing-column-properties">Customizing Column Properties</a><ul> <li><a class="reference internal" href="#naming-columns-distinctly-from-attribute-names">Naming Columns Distinctly from Attribute Names</a></li> <li><a class="reference internal" href="#automating-column-naming-schemes-from-reflected-tables">Automating Column Naming Schemes from Reflected Tables</a></li> <li><a class="reference internal" href="#naming-all-columns-with-a-prefix">Naming All Columns with a Prefix</a></li> <li><a class="reference internal" href="#using-column-property-for-column-level-options">Using column_property for column level options</a></li> <li><a class="reference internal" href="#mapping-a-subset-of-table-columns">Mapping a Subset of Table Columns</a></li> </ul> </li> <li><a class="reference internal" href="#deferred-column-loading">Deferred Column Loading</a><ul> <li><a class="reference internal" href="#column-deferral-api">Column Deferral API</a></li> </ul> </li> <li><a class="reference internal" href="#sql-expressions-as-mapped-attributes">SQL Expressions as Mapped Attributes</a><ul> <li><a class="reference internal" href="#using-a-hybrid">Using a Hybrid</a></li> <li><a class="reference internal" href="#using-column-property">Using column_property</a></li> <li><a class="reference internal" href="#using-a-plain-descriptor">Using a plain descriptor</a></li> </ul> </li> <li><a class="reference internal" href="#changing-attribute-behavior">Changing Attribute Behavior</a><ul> <li><a class="reference internal" href="#simple-validators">Simple Validators</a></li> <li><a class="reference internal" href="#using-descriptors-and-hybrids">Using Descriptors and Hybrids</a></li> <li><a class="reference internal" href="#id2">Synonyms</a></li> <li><a class="reference internal" href="#operator-customization">Operator Customization</a></li> </ul> </li> <li><a class="reference internal" href="#composite-column-types">Composite Column Types</a><ul> <li><a class="reference internal" href="#tracking-in-place-mutations-on-composites">Tracking In-Place Mutations on Composites</a></li> <li><a class="reference internal" href="#redefining-comparison-operations-for-composites">Redefining Comparison Operations for Composites</a></li> </ul> </li> <li><a class="reference internal" href="#mapping-a-class-against-multiple-tables">Mapping a Class against Multiple Tables</a></li> <li><a class="reference internal" href="#mapping-a-class-against-arbitrary-selects">Mapping a Class against Arbitrary Selects</a></li> <li><a class="reference internal" href="#multiple-mappers-for-one-class">Multiple Mappers for One Class</a></li> <li><a class="reference internal" href="#constructors-and-object-initialization">Constructors and Object Initialization</a></li> <li><a class="reference internal" href="#configuring-a-version-counter">Configuring a Version Counter</a><ul> <li><a class="reference internal" href="#simple-version-counting">Simple Version Counting</a></li> <li><a class="reference internal" href="#custom-version-counters-types">Custom Version Counters / Types</a></li> </ul> </li> <li><a class="reference internal" href="#class-mapping-api">Class Mapping API</a></li> </ul> </li> </ul> </div> </div> <div id="docs-body" class="withsidebar" > <span class="target" id="module-sqlalchemy.orm"></span><div class="section" id="mapper-configuration"> <span id="mapper-config-toplevel"></span><h1>Mapper Configuration<a class="headerlink" href="#mapper-configuration" title="Permalink to this headline">¶</a></h1> <p>This section describes a variety of configurational patterns that are usable with mappers. It assumes you’ve worked through <a class="reference internal" href="tutorial.html"><em>Object Relational Tutorial</em></a> and know how to construct and use rudimentary mappers and relationships.</p> <div class="section" id="classical-mappings"> <span id="classical-mapping"></span><h2>Classical Mappings<a class="headerlink" href="#classical-mappings" title="Permalink to this headline">¶</a></h2> <p>A <em>Classical Mapping</em> refers to the configuration of a mapped class using the <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> function, without using the Declarative system. As an example, start with the declarative mapping introduced in <a class="reference internal" href="tutorial.html"><em>Object Relational Tutorial</em></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'users'</span> <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> <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> <span class="n">fullname</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="n">password</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> </div> <p>In “classical” form, the table metadata is created separately with the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> construct, then associated with the <tt class="docutils literal"><span class="pre">User</span></tt> class via the <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> function:</p> <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">Table</span><span class="p">,</span> <span class="n">MetaData</span><span class="p">,</span> <span class="n">Column</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">,</span> <span class="n">Integer</span><span class="p">,</span> <span class="n">String</span> <span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">mapper</span> <span class="n">metadata</span> <span class="o">=</span> <span class="n">MetaData</span><span class="p">()</span> <span class="n">user</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s">'user'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="n">Column</span><span class="p">(</span><span class="s">'id'</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> <span class="n">Column</span><span class="p">(</span><span class="s">'name'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">50</span><span class="p">)),</span> <span class="n">Column</span><span class="p">(</span><span class="s">'fullname'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">50</span><span class="p">)),</span> <span class="n">Column</span><span class="p">(</span><span class="s">'password'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">12</span><span class="p">))</span> <span class="p">)</span> <span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">fullname</span><span class="p">,</span> <span class="n">password</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span> <span class="bp">self</span><span class="o">.</span><span class="n">fullname</span> <span class="o">=</span> <span class="n">fullname</span> <span class="bp">self</span><span class="o">.</span><span class="n">password</span> <span class="o">=</span> <span class="n">password</span> <span class="n">mapper</span><span class="p">(</span><span class="n">User</span><span class="p">,</span> <span class="n">user</span><span class="p">)</span></pre></div> </div> <p>Information about mapped attributes, such as relationships to other classes, are provided via the <tt class="docutils literal"><span class="pre">properties</span></tt> dictionary. The example below illustrates a second <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> object, mapped to a class called <tt class="docutils literal"><span class="pre">Address</span></tt>, then linked to <tt class="docutils literal"><span class="pre">User</span></tt> via <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">address</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s">'address'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="n">Column</span><span class="p">(</span><span class="s">'id'</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> <span class="n">Column</span><span class="p">(</span><span class="s">'user_id'</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">'user.id'</span><span class="p">)),</span> <span class="n">Column</span><span class="p">(</span><span class="s">'email_address'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">50</span><span class="p">))</span> <span class="p">)</span> <span class="n">mapper</span><span class="p">(</span><span class="n">User</span><span class="p">,</span> <span class="n">user</span><span class="p">,</span> <span class="n">properties</span><span class="o">=</span><span class="p">{</span> <span class="s">'addresses'</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">backref</span><span class="o">=</span><span class="s">'user'</span><span class="p">,</span> <span class="n">order_by</span><span class="o">=</span><span class="n">address</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="p">)</span> <span class="p">})</span> <span class="n">mapper</span><span class="p">(</span><span class="n">Address</span><span class="p">,</span> <span class="n">address</span><span class="p">)</span></pre></div> </div> <p>When using classical mappings, classes must be provided directly without the benefit of the “string lookup” system provided by Declarative. SQL expressions are typically specified in terms of the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> objects, i.e. <tt class="docutils literal"><span class="pre">address.c.id</span></tt> above for the <tt class="docutils literal"><span class="pre">Address</span></tt> relationship, and not <tt class="docutils literal"><span class="pre">Address.id</span></tt>, as <tt class="docutils literal"><span class="pre">Address</span></tt> may not yet be linked to table metadata, nor can we specify a string here.</p> <p>Some examples in the documentation still use the classical approach, but note that the classical as well as Declarative approaches are <strong>fully interchangeable</strong>. Both systems ultimately create the same configuration, consisting of a <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a>, user-defined class, linked together with a <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a>. When we talk about “the behavior of <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a>”, this includes when using the Declarative system as well - it’s still used, just behind the scenes.</p> </div> <div class="section" id="customizing-column-properties"> <h2>Customizing Column Properties<a class="headerlink" href="#customizing-column-properties" title="Permalink to this headline">¶</a></h2> <p>The default behavior of <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> is to assemble all the columns in the mapped <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> into mapped object attributes, each of which are named according to the name of the column itself (specifically, the <tt class="docutils literal"><span class="pre">key</span></tt> attribute of <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a>). This behavior can be modified in several ways.</p> <div class="section" id="naming-columns-distinctly-from-attribute-names"> <span id="mapper-column-distinct-names"></span><h3>Naming Columns Distinctly from Attribute Names<a class="headerlink" href="#naming-columns-distinctly-from-attribute-names" title="Permalink to this headline">¶</a></h3> <p>A mapping by default shares the same name for a <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> as that of the mapped attribute - specifically it matches the <tt class="xref py py-attr docutils literal"><span class="pre">Column.key</span></tt> attribute on <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a>, which by default is the same as the <tt class="xref py py-attr docutils literal"><span class="pre">Column.name</span></tt>.</p> <p>The name assigned to the Python attribute which maps to <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> can be different from either <tt class="xref py py-attr docutils literal"><span class="pre">Column.name</span></tt> or <tt class="xref py py-attr docutils literal"><span class="pre">Column.key</span></tt> just by assigning it that way, as we illustrate here in a Declarative mapping:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'user'</span> <span class="nb">id</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="s">'user_id'</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> <span class="n">name</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="s">'user_name'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">50</span><span class="p">))</span></pre></div> </div> <p>Where above <tt class="docutils literal"><span class="pre">User.id</span></tt> resolves to a column named <tt class="docutils literal"><span class="pre">user_id</span></tt> and <tt class="docutils literal"><span class="pre">User.name</span></tt> resolves to a column named <tt class="docutils literal"><span class="pre">user_name</span></tt>.</p> <p>When mapping to an existing table, the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> object can be referenced directly:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__table__</span> <span class="o">=</span> <span class="n">user_table</span> <span class="nb">id</span> <span class="o">=</span> <span class="n">user_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">user_id</span> <span class="n">name</span> <span class="o">=</span> <span class="n">user_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">user_name</span></pre></div> </div> <p>Or in a classical mapping, placed in the <tt class="docutils literal"><span class="pre">properties</span></tt> dictionary with the desired key:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">mapper</span><span class="p">(</span><span class="n">User</span><span class="p">,</span> <span class="n">user_table</span><span class="p">,</span> <span class="n">properties</span><span class="o">=</span><span class="p">{</span> <span class="s">'id'</span><span class="p">:</span> <span class="n">user_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> <span class="s">'name'</span><span class="p">:</span> <span class="n">user_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">user_name</span><span class="p">,</span> <span class="p">})</span></pre></div> </div> <p>In the next section we’ll examine the usage of <tt class="docutils literal"><span class="pre">.key</span></tt> more closely.</p> </div> <div class="section" id="automating-column-naming-schemes-from-reflected-tables"> <span id="mapper-automated-reflection-schemes"></span><h3>Automating Column Naming Schemes from Reflected Tables<a class="headerlink" href="#automating-column-naming-schemes-from-reflected-tables" title="Permalink to this headline">¶</a></h3> <p>In the previous section <a class="reference internal" href="#mapper-column-distinct-names"><em>Naming Columns Distinctly from Attribute Names</em></a>, we showed how a <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> explicitly mapped to a class can have a different attribute name than the column. But what if we aren’t listing out <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> objects explicitly, and instead are automating the production of <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> objects using reflection (e.g. as described in <a class="reference internal" href="../core/reflection.html"><em>Reflecting Database Objects</em></a>)? In this case we can make use of the <a class="reference internal" href="../core/events.html#sqlalchemy.events.DDLEvents.column_reflect" title="sqlalchemy.events.DDLEvents.column_reflect"><tt class="xref py py-meth docutils literal"><span class="pre">DDLEvents.column_reflect()</span></tt></a> event to intercept the production of <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> objects and provide them with the <tt class="xref py py-attr docutils literal"><span class="pre">Column.key</span></tt> of our choice:</p> <div class="highlight-python"><div class="highlight"><pre><span class="nd">@event.listens_for</span><span class="p">(</span><span class="n">Table</span><span class="p">,</span> <span class="s">"column_reflect"</span><span class="p">)</span> <span class="k">def</span> <span class="nf">column_reflect</span><span class="p">(</span><span class="n">inspector</span><span class="p">,</span> <span class="n">table</span><span class="p">,</span> <span class="n">column_info</span><span class="p">):</span> <span class="c"># set column.key = "attr_<lower_case_name>"</span> <span class="n">column_info</span><span class="p">[</span><span class="s">'key'</span><span class="p">]</span> <span class="o">=</span> <span class="s">"attr_</span><span class="si">%s</span><span class="s">"</span> <span class="o">%</span> <span class="n">column_info</span><span class="p">[</span><span class="s">'name'</span><span class="p">]</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span></pre></div> </div> <p>With the above event, the reflection of <a class="reference internal" href="../core/metadata.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 be intercepted with our event that adds a new ”.key” element, such as in a mapping as below:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">MyClass</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__table__</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s">"some_table"</span><span class="p">,</span> <span class="n">Base</span><span class="o">.</span><span class="n">metadata</span><span class="p">,</span> <span class="n">autoload</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">autoload_with</span><span class="o">=</span><span class="n">some_engine</span><span class="p">)</span></pre></div> </div> <p>If we want to qualify our event to only react for the specific <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.MetaData" title="sqlalchemy.schema.MetaData"><tt class="xref py py-class docutils literal"><span class="pre">MetaData</span></tt></a> object above, we can check for it in our event:</p> <div class="highlight-python"><div class="highlight"><pre><span class="nd">@event.listens_for</span><span class="p">(</span><span class="n">Table</span><span class="p">,</span> <span class="s">"column_reflect"</span><span class="p">)</span> <span class="k">def</span> <span class="nf">column_reflect</span><span class="p">(</span><span class="n">inspector</span><span class="p">,</span> <span class="n">table</span><span class="p">,</span> <span class="n">column_info</span><span class="p">):</span> <span class="k">if</span> <span class="n">table</span><span class="o">.</span><span class="n">metadata</span> <span class="ow">is</span> <span class="n">Base</span><span class="o">.</span><span class="n">metadata</span><span class="p">:</span> <span class="c"># set column.key = "attr_<lower_case_name>"</span> <span class="n">column_info</span><span class="p">[</span><span class="s">'key'</span><span class="p">]</span> <span class="o">=</span> <span class="s">"attr_</span><span class="si">%s</span><span class="s">"</span> <span class="o">%</span> <span class="n">column_info</span><span class="p">[</span><span class="s">'name'</span><span class="p">]</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span></pre></div> </div> </div> <div class="section" id="naming-all-columns-with-a-prefix"> <span id="column-prefix"></span><h3>Naming All Columns with a Prefix<a class="headerlink" href="#naming-all-columns-with-a-prefix" title="Permalink to this headline">¶</a></h3> <p>A quick approach to prefix column names, typically when mapping to an existing <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> object, is to use <tt class="docutils literal"><span class="pre">column_prefix</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__table__</span> <span class="o">=</span> <span class="n">user_table</span> <span class="n">__mapper_args__</span> <span class="o">=</span> <span class="p">{</span><span class="s">'column_prefix'</span><span class="p">:</span><span class="s">'_'</span><span class="p">}</span></pre></div> </div> <p>The above will place attribute names such as <tt class="docutils literal"><span class="pre">_user_id</span></tt>, <tt class="docutils literal"><span class="pre">_user_name</span></tt>, <tt class="docutils literal"><span class="pre">_password</span></tt> etc. on the mapped <tt class="docutils literal"><span class="pre">User</span></tt> class.</p> <p>This approach is uncommon in modern usage. For dealing with reflected tables, a more flexible approach is to use that described in <a class="reference internal" href="#mapper-automated-reflection-schemes"><em>Automating Column Naming Schemes from Reflected Tables</em></a>.</p> </div> <div class="section" id="using-column-property-for-column-level-options"> <h3>Using column_property for column level options<a class="headerlink" href="#using-column-property-for-column-level-options" title="Permalink to this headline">¶</a></h3> <p>Options can be specified when mapping a <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> using the <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">column_property()</span></tt></a> function. This function explicitly creates the <a class="reference internal" href="internals.html#sqlalchemy.orm.properties.ColumnProperty" title="sqlalchemy.orm.properties.ColumnProperty"><tt class="xref py py-class docutils literal"><span class="pre">ColumnProperty</span></tt></a> used by the <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> to keep track of the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a>; normally, the <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> creates this automatically. Using <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">column_property()</span></tt></a>, we can pass additional arguments about how we’d like the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> to be mapped. Below, we pass an option <tt class="docutils literal"><span class="pre">active_history</span></tt>, which specifies that a change to this column’s value should result in the former value being loaded first:</p> <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">column_property</span> <span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'user'</span> <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> <span class="n">name</span> <span class="o">=</span> <span class="n">column_property</span><span class="p">(</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> <span class="n">active_history</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span></pre></div> </div> <p><a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">column_property()</span></tt></a> is also used to map a single attribute to multiple columns. This use case arises when mapping to a <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.join" title="sqlalchemy.sql.expression.join"><tt class="xref py py-func docutils literal"><span class="pre">join()</span></tt></a> which has attributes which are equated to each other:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__table__</span> <span class="o">=</span> <span class="n">user</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">address</span><span class="p">)</span> <span class="c"># assign "user.id", "address.user_id" to the</span> <span class="c"># "id" attribute</span> <span class="nb">id</span> <span class="o">=</span> <span class="n">column_property</span><span class="p">(</span><span class="n">user_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="p">,</span> <span class="n">address_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> </div> <p>For more examples featuring this usage, see <a class="reference internal" href="#maptojoin"><em>Mapping a Class against Multiple Tables</em></a>.</p> <p>Another place where <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">column_property()</span></tt></a> is needed is to specify SQL expressions as mapped attributes, such as below where we create an attribute <tt class="docutils literal"><span class="pre">fullname</span></tt> that is the string concatenation of the <tt class="docutils literal"><span class="pre">firstname</span></tt> and <tt class="docutils literal"><span class="pre">lastname</span></tt> columns:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'user'</span> <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> <span class="n">firstname</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> <span class="n">lastname</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> <span class="n">fullname</span> <span class="o">=</span> <span class="n">column_property</span><span class="p">(</span><span class="n">firstname</span> <span class="o">+</span> <span class="s">" "</span> <span class="o">+</span> <span class="n">lastname</span><span class="p">)</span></pre></div> </div> <p>See examples of this usage at <a class="reference internal" href="#mapper-sql-expressions"><em>SQL Expressions as Mapped Attributes</em></a>.</p> <dl class="function"> <dt id="sqlalchemy.orm.column_property"> <tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">column_property</tt><big>(</big><em>*cols</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.column_property" title="Permalink to this definition">¶</a></dt> <dd><p>Provide a column-level property for use with a Mapper.</p> <p>Column-based properties can normally be applied to the mapper’s <tt class="docutils literal"><span class="pre">properties</span></tt> dictionary using the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> element directly. Use this function when the given column is not directly present within the mapper’s selectable; examples include SQL expressions, functions, and scalar SELECT queries.</p> <p>Columns that aren’t present in the mapper’s selectable won’t be persisted by the mapper and are effectively “read-only” attributes.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><span class="target" id="sqlalchemy.orm.column_property.params.*cols"></span><strong>*cols</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.column_property.params.*cols">¶</a> – list of Column objects to be mapped.</li> <li><span class="target" id="sqlalchemy.orm.column_property.params.active_history"></span><strong>active_history=False</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.column_property.params.active_history">¶</a> – <p>When <tt class="docutils literal"><span class="pre">True</span></tt>, indicates that the “previous” value for a scalar attribute should be loaded when replaced, if not already loaded. Normally, history tracking logic for simple non-primary-key scalar values only needs to be aware of the “new” value in order to perform a flush. This flag is available for applications that make use of <a class="reference internal" href="session.html#sqlalchemy.orm.attributes.get_history" title="sqlalchemy.orm.attributes.get_history"><tt class="xref py py-func docutils literal"><span class="pre">attributes.get_history()</span></tt></a> or <a class="reference internal" href="session.html#sqlalchemy.orm.session.Session.is_modified" title="sqlalchemy.orm.session.Session.is_modified"><tt class="xref py py-meth docutils literal"><span class="pre">Session.is_modified()</span></tt></a> which also need to know the “previous” value of the attribute.</p> <div class="versionadded"> <p><span>New in version 0.6.6.</span></p> </div> </li> <li><span class="target" id="sqlalchemy.orm.column_property.params.comparator_factory"></span><strong>comparator_factory</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.column_property.params.comparator_factory">¶</a> – a class which extends <a class="reference internal" href="internals.html#sqlalchemy.orm.properties.ColumnProperty.Comparator" title="sqlalchemy.orm.properties.ColumnProperty.Comparator"><tt class="xref py py-class docutils literal"><span class="pre">ColumnProperty.Comparator</span></tt></a> which provides custom SQL clause generation for comparison operations.</li> <li><span class="target" id="sqlalchemy.orm.column_property.params.group"></span><strong>group</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.column_property.params.group">¶</a> – a group name for this property when marked as deferred.</li> <li><span class="target" id="sqlalchemy.orm.column_property.params.deferred"></span><strong>deferred</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.column_property.params.deferred">¶</a> – when True, the column property is “deferred”, meaning that it does not load immediately, and is instead loaded when the attribute is first accessed on an instance. See also <a class="reference internal" href="#sqlalchemy.orm.deferred" title="sqlalchemy.orm.deferred"><tt class="xref py py-func docutils literal"><span class="pre">deferred()</span></tt></a>.</li> <li><span class="target" id="sqlalchemy.orm.column_property.params.doc"></span><strong>doc</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.column_property.params.doc">¶</a> – optional string that will be applied as the doc on the class-bound descriptor.</li> <li><span class="target" id="sqlalchemy.orm.column_property.params.expire_on_flush"></span><strong>expire_on_flush=True</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.column_property.params.expire_on_flush">¶</a> – <p>Disable expiry on flush. A column_property() which refers to a SQL expression (and not a single table-bound column) is considered to be a “read only” property; populating it has no effect on the state of data, and it can only return database state. For this reason a column_property()’s value is expired whenever the parent object is involved in a flush, that is, has any kind of “dirty” state within a flush. Setting this parameter to <tt class="docutils literal"><span class="pre">False</span></tt> will have the effect of leaving any existing value present after the flush proceeds. Note however that the <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> with default expiration settings still expires all attributes after a <a class="reference internal" href="session.html#sqlalchemy.orm.session.Session.commit" title="sqlalchemy.orm.session.Session.commit"><tt class="xref py py-meth docutils literal"><span class="pre">Session.commit()</span></tt></a> call, however.</p> <div class="versionadded"> <p><span>New in version 0.7.3.</span></p> </div> </li> <li><span class="target" id="sqlalchemy.orm.column_property.params.info"></span><strong>info</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.column_property.params.info">¶</a> – <p>Optional data dictionary which will be populated into the <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> <div class="versionadded"> <p><span>New in version 0.8.</span></p> </div> </li> <li><span class="target" id="sqlalchemy.orm.column_property.params.extension"></span><strong>extension</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.column_property.params.extension">¶</a> – an <a class="reference internal" href="deprecated.html#sqlalchemy.orm.interfaces.AttributeExtension" title="sqlalchemy.orm.interfaces.AttributeExtension"><tt class="xref py py-class docutils literal"><span class="pre">AttributeExtension</span></tt></a> instance, or list of extensions, which will be prepended to the list of attribute listeners for the resulting descriptor placed on the class. <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> </ul> </td> </tr> </tbody> </table> </dd></dl> </div> <div class="section" id="mapping-a-subset-of-table-columns"> <span id="include-exclude-cols"></span><h3>Mapping a Subset of Table Columns<a class="headerlink" href="#mapping-a-subset-of-table-columns" title="Permalink to this headline">¶</a></h3> <p>Sometimes, a <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> object was made available using the reflection process described at <a class="reference internal" href="../core/reflection.html#metadata-reflection"><em>Reflecting Database Objects</em></a> to load the table’s structure from the database. For such a table that has lots of columns that don’t need to be referenced in the application, the <tt class="docutils literal"><span class="pre">include_properties</span></tt> or <tt class="docutils literal"><span class="pre">exclude_properties</span></tt> arguments can specify that only a subset of columns should be mapped. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__table__</span> <span class="o">=</span> <span class="n">user_table</span> <span class="n">__mapper_args__</span> <span class="o">=</span> <span class="p">{</span> <span class="s">'include_properties'</span> <span class="p">:[</span><span class="s">'user_id'</span><span class="p">,</span> <span class="s">'user_name'</span><span class="p">]</span> <span class="p">}</span></pre></div> </div> <p>...will map the <tt class="docutils literal"><span class="pre">User</span></tt> class to the <tt class="docutils literal"><span class="pre">user_table</span></tt> table, only including the <tt class="docutils literal"><span class="pre">user_id</span></tt> and <tt class="docutils literal"><span class="pre">user_name</span></tt> columns - the rest are not referenced. Similarly:</p> <div class="highlight-python"><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> <span class="n">__table__</span> <span class="o">=</span> <span class="n">address_table</span> <span class="n">__mapper_args__</span> <span class="o">=</span> <span class="p">{</span> <span class="s">'exclude_properties'</span> <span class="p">:</span> <span class="p">[</span><span class="s">'street'</span><span class="p">,</span> <span class="s">'city'</span><span class="p">,</span> <span class="s">'state'</span><span class="p">,</span> <span class="s">'zip'</span><span class="p">]</span> <span class="p">}</span></pre></div> </div> <p>...will map the <tt class="docutils literal"><span class="pre">Address</span></tt> class to the <tt class="docutils literal"><span class="pre">address_table</span></tt> table, including all columns present except <tt class="docutils literal"><span class="pre">street</span></tt>, <tt class="docutils literal"><span class="pre">city</span></tt>, <tt class="docutils literal"><span class="pre">state</span></tt>, and <tt class="docutils literal"><span class="pre">zip</span></tt>.</p> <p>When this mapping is used, the columns that are not included will not be referenced in any SELECT statements emitted by <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>, nor will there be any mapped attribute on the mapped class which represents the column; assigning an attribute of that name will have no effect beyond that of a normal Python attribute assignment.</p> <p>In some cases, multiple columns may have the same name, such as when mapping to a join of two or more tables that share some column name. <tt class="docutils literal"><span class="pre">include_properties</span></tt> and <tt class="docutils literal"><span class="pre">exclude_properties</span></tt> can also accommodate <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> objects to more accurately describe which columns should be included or excluded:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">UserAddress</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__table__</span> <span class="o">=</span> <span class="n">user_table</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">addresses_table</span><span class="p">)</span> <span class="n">__mapper_args__</span> <span class="o">=</span> <span class="p">{</span> <span class="s">'exclude_properties'</span> <span class="p">:[</span><span class="n">address_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="p">],</span> <span class="s">'primary_key'</span> <span class="p">:</span> <span class="p">[</span><span class="n">user_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="p">]</span> <span class="p">}</span></pre></div> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">insert and update defaults configured on individual <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> objects, i.e. those described at <em class="xref std std-ref">metadata_defaults</em> including those configured by the <tt class="docutils literal"><span class="pre">default</span></tt>, <tt class="docutils literal"><span class="pre">update</span></tt>, <tt class="docutils literal"><span class="pre">server_default</span></tt> and <tt class="docutils literal"><span class="pre">server_onupdate</span></tt> arguments, will continue to function normally even if those <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> objects are not mapped. This is because in the case of <tt class="docutils literal"><span class="pre">default</span></tt> and <tt class="docutils literal"><span class="pre">update</span></tt>, the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> object is still present on the underlying <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a>, thus allowing the default functions to take place when the ORM emits an INSERT or UPDATE, and in the case of <tt class="docutils literal"><span class="pre">server_default</span></tt> and <tt class="docutils literal"><span class="pre">server_onupdate</span></tt>, the relational database itself maintains these functions.</p> </div> </div> </div> <div class="section" id="deferred-column-loading"> <span id="deferred"></span><h2>Deferred Column Loading<a class="headerlink" href="#deferred-column-loading" title="Permalink to this headline">¶</a></h2> <p>This feature allows particular columns of a table be loaded only upon direct access, instead of when the entity is queried using <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>. This feature is useful when one wants to avoid loading a large text or binary field into memory when it’s not needed. Individual columns can be lazy loaded by themselves or placed into groups that lazy-load together, using the <a class="reference internal" href="#sqlalchemy.orm.deferred" title="sqlalchemy.orm.deferred"><tt class="xref py py-func docutils literal"><span class="pre">orm.deferred()</span></tt></a> function to mark them as “deferred”. In the example below, we define a mapping that will load each of <tt class="docutils literal"><span class="pre">.excerpt</span></tt> and <tt class="docutils literal"><span class="pre">.photo</span></tt> in separate, individual-row SELECT statements when each attribute is first referenced on the individual object instance:</p> <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">deferred</span> <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">String</span><span class="p">,</span> <span class="n">Text</span><span class="p">,</span> <span class="n">Binary</span><span class="p">,</span> <span class="n">Column</span> <span class="k">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'book'</span> <span class="n">book_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> <span class="n">title</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">200</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span> <span class="n">summary</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">2000</span><span class="p">))</span> <span class="n">excerpt</span> <span class="o">=</span> <span class="n">deferred</span><span class="p">(</span><span class="n">Column</span><span class="p">(</span><span class="n">Text</span><span class="p">))</span> <span class="n">photo</span> <span class="o">=</span> <span class="n">deferred</span><span class="p">(</span><span class="n">Column</span><span class="p">(</span><span class="n">Binary</span><span class="p">))</span></pre></div> </div> <p>Classical mappings as always place the usage of <a class="reference internal" href="#sqlalchemy.orm.deferred" title="sqlalchemy.orm.deferred"><tt class="xref py py-func docutils literal"><span class="pre">orm.deferred()</span></tt></a> in the <tt class="docutils literal"><span class="pre">properties</span></tt> dictionary against the table-bound <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">mapper</span><span class="p">(</span><span class="n">Book</span><span class="p">,</span> <span class="n">book_table</span><span class="p">,</span> <span class="n">properties</span><span class="o">=</span><span class="p">{</span> <span class="s">'photo'</span><span class="p">:</span><span class="n">deferred</span><span class="p">(</span><span class="n">book_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">photo</span><span class="p">)</span> <span class="p">})</span></pre></div> </div> <p>Deferred columns can be associated with a “group” name, so that they load together when any of them are first accessed. The example below defines a mapping with a <tt class="docutils literal"><span class="pre">photos</span></tt> deferred group. When one <tt class="docutils literal"><span class="pre">.photo</span></tt> is accessed, all three photos will be loaded in one SELECT statement. The <tt class="docutils literal"><span class="pre">.excerpt</span></tt> will be loaded separately when it is accessed:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'book'</span> <span class="n">book_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> <span class="n">title</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">200</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span> <span class="n">summary</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">2000</span><span class="p">))</span> <span class="n">excerpt</span> <span class="o">=</span> <span class="n">deferred</span><span class="p">(</span><span class="n">Column</span><span class="p">(</span><span class="n">Text</span><span class="p">))</span> <span class="n">photo1</span> <span class="o">=</span> <span class="n">deferred</span><span class="p">(</span><span class="n">Column</span><span class="p">(</span><span class="n">Binary</span><span class="p">),</span> <span class="n">group</span><span class="o">=</span><span class="s">'photos'</span><span class="p">)</span> <span class="n">photo2</span> <span class="o">=</span> <span class="n">deferred</span><span class="p">(</span><span class="n">Column</span><span class="p">(</span><span class="n">Binary</span><span class="p">),</span> <span class="n">group</span><span class="o">=</span><span class="s">'photos'</span><span class="p">)</span> <span class="n">photo3</span> <span class="o">=</span> <span class="n">deferred</span><span class="p">(</span><span class="n">Column</span><span class="p">(</span><span class="n">Binary</span><span class="p">),</span> <span class="n">group</span><span class="o">=</span><span class="s">'photos'</span><span class="p">)</span></pre></div> </div> <p>You can defer or undefer columns at the <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> level using the <a class="reference internal" href="#sqlalchemy.orm.defer" title="sqlalchemy.orm.defer"><tt class="xref py py-func docutils literal"><span class="pre">orm.defer()</span></tt></a> and <a class="reference internal" href="#sqlalchemy.orm.undefer" title="sqlalchemy.orm.undefer"><tt class="xref py py-func docutils literal"><span class="pre">orm.undefer()</span></tt></a> query options:</p> <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">defer</span><span class="p">,</span> <span class="n">undefer</span> <span class="n">query</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">Book</span><span class="p">)</span> <span class="n">query</span><span class="o">.</span><span class="n">options</span><span class="p">(</span><span class="n">defer</span><span class="p">(</span><span class="s">'summary'</span><span class="p">))</span><span class="o">.</span><span class="n">all</span><span class="p">()</span> <span class="n">query</span><span class="o">.</span><span class="n">options</span><span class="p">(</span><span class="n">undefer</span><span class="p">(</span><span class="s">'excerpt'</span><span class="p">))</span><span class="o">.</span><span class="n">all</span><span class="p">()</span></pre></div> </div> <p>And an entire “deferred group”, i.e. which uses the <tt class="docutils literal"><span class="pre">group</span></tt> keyword argument to <a class="reference internal" href="#sqlalchemy.orm.deferred" title="sqlalchemy.orm.deferred"><tt class="xref py py-func docutils literal"><span class="pre">orm.deferred()</span></tt></a>, can be undeferred using <a class="reference internal" href="#sqlalchemy.orm.undefer_group" title="sqlalchemy.orm.undefer_group"><tt class="xref py py-func docutils literal"><span class="pre">orm.undefer_group()</span></tt></a>, sending in the group name:</p> <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">undefer_group</span> <span class="n">query</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">Book</span><span class="p">)</span> <span class="n">query</span><span class="o">.</span><span class="n">options</span><span class="p">(</span><span class="n">undefer_group</span><span class="p">(</span><span class="s">'photos'</span><span class="p">))</span><span class="o">.</span><span class="n">all</span><span class="p">()</span></pre></div> </div> <div class="section" id="column-deferral-api"> <h3>Column Deferral API<a class="headerlink" href="#column-deferral-api" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="sqlalchemy.orm.deferred"> <tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">deferred</tt><big>(</big><em>*columns</em>, <em>**kwargs</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.deferred" title="Permalink to this definition">¶</a></dt> <dd><p>Return a <tt class="xref py py-class docutils literal"><span class="pre">DeferredColumnProperty</span></tt>, which indicates this object attributes should only be loaded from its corresponding table column when first accessed.</p> <p>Used with the “properties” dictionary sent to <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a>.</p> <p>See also:</p> <p><a class="reference internal" href="#deferred"><em>Deferred Column Loading</em></a></p> </dd></dl> <dl class="function"> <dt id="sqlalchemy.orm.defer"> <tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">defer</tt><big>(</big><em>*key</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.defer" title="Permalink to this definition">¶</a></dt> <dd><p>Return a <tt class="xref py py-class docutils literal"><span class="pre">MapperOption</span></tt> that will convert the column property of the given name into a deferred load.</p> <p>Used with <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query.options" title="sqlalchemy.orm.query.Query.options"><tt class="xref py py-meth docutils literal"><span class="pre">Query.options()</span></tt></a>.</p> <p>e.g.:</p> <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">defer</span> <span class="n">query</span><span class="p">(</span><span class="n">MyClass</span><span class="p">)</span><span class="o">.</span><span class="n">options</span><span class="p">(</span><span class="n">defer</span><span class="p">(</span><span class="s">"attribute_one"</span><span class="p">),</span> <span class="n">defer</span><span class="p">(</span><span class="s">"attribute_two"</span><span class="p">))</span></pre></div> </div> <p>A class bound descriptor is also accepted:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">query</span><span class="p">(</span><span class="n">MyClass</span><span class="p">)</span><span class="o">.</span><span class="n">options</span><span class="p">(</span> <span class="n">defer</span><span class="p">(</span><span class="n">MyClass</span><span class="o">.</span><span class="n">attribute_one</span><span class="p">),</span> <span class="n">defer</span><span class="p">(</span><span class="n">MyClass</span><span class="o">.</span><span class="n">attribute_two</span><span class="p">))</span></pre></div> </div> <p>A “path” can be specified onto a related or collection object using a dotted name. The <a class="reference internal" href="#sqlalchemy.orm.defer" title="sqlalchemy.orm.defer"><tt class="xref py py-func docutils literal"><span class="pre">orm.defer()</span></tt></a> option will be applied to that object when loaded:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">query</span><span class="p">(</span><span class="n">MyClass</span><span class="p">)</span><span class="o">.</span><span class="n">options</span><span class="p">(</span> <span class="n">defer</span><span class="p">(</span><span class="s">"related.attribute_one"</span><span class="p">),</span> <span class="n">defer</span><span class="p">(</span><span class="s">"related.attribute_two"</span><span class="p">))</span></pre></div> </div> <p>To specify a path via class, send multiple arguments:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">query</span><span class="p">(</span><span class="n">MyClass</span><span class="p">)</span><span class="o">.</span><span class="n">options</span><span class="p">(</span> <span class="n">defer</span><span class="p">(</span><span class="n">MyClass</span><span class="o">.</span><span class="n">related</span><span class="p">,</span> <span class="n">MyOtherClass</span><span class="o">.</span><span class="n">attribute_one</span><span class="p">),</span> <span class="n">defer</span><span class="p">(</span><span class="n">MyClass</span><span class="o">.</span><span class="n">related</span><span class="p">,</span> <span class="n">MyOtherClass</span><span class="o">.</span><span class="n">attribute_two</span><span class="p">))</span></pre></div> </div> <p>See also:</p> <p><a class="reference internal" href="#deferred"><em>Deferred Column Loading</em></a></p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><span class="target" id="sqlalchemy.orm.defer.params.*key"></span><strong>*key</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.defer.params.*key">¶</a> – A key representing an individual path. Multiple entries are accepted to allow a multiple-token path for a single target, not multiple targets.</td> </tr> </tbody> </table> </dd></dl> <dl class="function"> <dt id="sqlalchemy.orm.undefer"> <tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">undefer</tt><big>(</big><em>*key</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.undefer" title="Permalink to this definition">¶</a></dt> <dd><p>Return a <tt class="xref py py-class docutils literal"><span class="pre">MapperOption</span></tt> that will convert the column property of the given name into a non-deferred (regular column) load.</p> <p>Used with <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query.options" title="sqlalchemy.orm.query.Query.options"><tt class="xref py py-meth docutils literal"><span class="pre">Query.options()</span></tt></a>.</p> <p>e.g.:</p> <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">undefer</span> <span class="n">query</span><span class="p">(</span><span class="n">MyClass</span><span class="p">)</span><span class="o">.</span><span class="n">options</span><span class="p">(</span> <span class="n">undefer</span><span class="p">(</span><span class="s">"attribute_one"</span><span class="p">),</span> <span class="n">undefer</span><span class="p">(</span><span class="s">"attribute_two"</span><span class="p">))</span></pre></div> </div> <p>A class bound descriptor is also accepted:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">query</span><span class="p">(</span><span class="n">MyClass</span><span class="p">)</span><span class="o">.</span><span class="n">options</span><span class="p">(</span> <span class="n">undefer</span><span class="p">(</span><span class="n">MyClass</span><span class="o">.</span><span class="n">attribute_one</span><span class="p">),</span> <span class="n">undefer</span><span class="p">(</span><span class="n">MyClass</span><span class="o">.</span><span class="n">attribute_two</span><span class="p">))</span></pre></div> </div> <p>A “path” can be specified onto a related or collection object using a dotted name. The <a class="reference internal" href="#sqlalchemy.orm.undefer" title="sqlalchemy.orm.undefer"><tt class="xref py py-func docutils literal"><span class="pre">orm.undefer()</span></tt></a> option will be applied to that object when loaded:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">query</span><span class="p">(</span><span class="n">MyClass</span><span class="p">)</span><span class="o">.</span><span class="n">options</span><span class="p">(</span> <span class="n">undefer</span><span class="p">(</span><span class="s">"related.attribute_one"</span><span class="p">),</span> <span class="n">undefer</span><span class="p">(</span><span class="s">"related.attribute_two"</span><span class="p">))</span></pre></div> </div> <p>To specify a path via class, send multiple arguments:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">query</span><span class="p">(</span><span class="n">MyClass</span><span class="p">)</span><span class="o">.</span><span class="n">options</span><span class="p">(</span> <span class="n">undefer</span><span class="p">(</span><span class="n">MyClass</span><span class="o">.</span><span class="n">related</span><span class="p">,</span> <span class="n">MyOtherClass</span><span class="o">.</span><span class="n">attribute_one</span><span class="p">),</span> <span class="n">undefer</span><span class="p">(</span><span class="n">MyClass</span><span class="o">.</span><span class="n">related</span><span class="p">,</span> <span class="n">MyOtherClass</span><span class="o">.</span><span class="n">attribute_two</span><span class="p">))</span></pre></div> </div> <p>See also:</p> <p><a class="reference internal" href="#sqlalchemy.orm.undefer_group" title="sqlalchemy.orm.undefer_group"><tt class="xref py py-func docutils literal"><span class="pre">orm.undefer_group()</span></tt></a> as a means to “undefer” a group of attributes at once.</p> <p><a class="reference internal" href="#deferred"><em>Deferred Column Loading</em></a></p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><span class="target" id="sqlalchemy.orm.undefer.params.*key"></span><strong>*key</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.undefer.params.*key">¶</a> – A key representing an individual path. Multiple entries are accepted to allow a multiple-token path for a single target, not multiple targets.</td> </tr> </tbody> </table> </dd></dl> <dl class="function"> <dt id="sqlalchemy.orm.undefer_group"> <tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">undefer_group</tt><big>(</big><em>name</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.undefer_group" title="Permalink to this definition">¶</a></dt> <dd><p>Return a <tt class="xref py py-class docutils literal"><span class="pre">MapperOption</span></tt> that will convert the given group of deferred column properties into a non-deferred (regular column) load.</p> <p>Used with <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query.options" title="sqlalchemy.orm.query.Query.options"><tt class="xref py py-meth docutils literal"><span class="pre">Query.options()</span></tt></a>.</p> <p>e.g.:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">query</span><span class="p">(</span><span class="n">MyClass</span><span class="p">)</span><span class="o">.</span><span class="n">options</span><span class="p">(</span><span class="n">undefer</span><span class="p">(</span><span class="s">"group_one"</span><span class="p">))</span></pre></div> </div> <p>See also:</p> <p><a class="reference internal" href="#deferred"><em>Deferred Column Loading</em></a></p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><span class="target" id="sqlalchemy.orm.undefer_group.params.name"></span><strong>name</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.undefer_group.params.name">¶</a> – String name of the deferred group. This name is established using the “group” name to the <a class="reference internal" href="#sqlalchemy.orm.deferred" title="sqlalchemy.orm.deferred"><tt class="xref py py-func docutils literal"><span class="pre">orm.deferred()</span></tt></a> configurational function.</td> </tr> </tbody> </table> </dd></dl> </div> </div> <div class="section" id="sql-expressions-as-mapped-attributes"> <span id="mapper-sql-expressions"></span><h2>SQL Expressions as Mapped Attributes<a class="headerlink" href="#sql-expressions-as-mapped-attributes" title="Permalink to this headline">¶</a></h2> <p>Attributes on a mapped class can be linked to SQL expressions, which can be used in queries.</p> <div class="section" id="using-a-hybrid"> <h3>Using a Hybrid<a class="headerlink" href="#using-a-hybrid" title="Permalink to this headline">¶</a></h3> <p>The easiest and most flexible way to link relatively simple SQL expressions to a class is to use a so-called “hybrid attribute”, described in the section <a class="reference internal" href="extensions/hybrid.html"><em>Hybrid Attributes</em></a>. The hybrid provides for an expression that works at both the Python level as well as at the SQL expression level. For example, below we map a class <tt class="docutils literal"><span class="pre">User</span></tt>, containing attributes <tt class="docutils literal"><span class="pre">firstname</span></tt> and <tt class="docutils literal"><span class="pre">lastname</span></tt>, and include a hybrid that will provide for us the <tt class="docutils literal"><span class="pre">fullname</span></tt>, which is the string concatenation of the two:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy.ext.hybrid</span> <span class="kn">import</span> <span class="n">hybrid_property</span> <span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'user'</span> <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> <span class="n">firstname</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> <span class="n">lastname</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> <span class="nd">@hybrid_property</span> <span class="k">def</span> <span class="nf">fullname</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">firstname</span> <span class="o">+</span> <span class="s">" "</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">lastname</span></pre></div> </div> <p>Above, the <tt class="docutils literal"><span class="pre">fullname</span></tt> attribute is interpreted at both the instance and class level, so that it is available from an instance:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">some_user</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">User</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span> <span class="k">print</span> <span class="n">some_user</span><span class="o">.</span><span class="n">fullname</span></pre></div> </div> <p>as well as usable wtihin queries:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">some_user</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">User</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">User</span><span class="o">.</span><span class="n">fullname</span> <span class="o">==</span> <span class="s">"John Smith"</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span></pre></div> </div> <p>The string concatenation example is a simple one, where the Python expression can be dual purposed at the instance and class level. Often, the SQL expression must be distinguished from the Python expression, which can be achieved using <a class="reference internal" href="extensions/hybrid.html#sqlalchemy.ext.hybrid.hybrid_property.expression" title="sqlalchemy.ext.hybrid.hybrid_property.expression"><tt class="xref py py-meth docutils literal"><span class="pre">hybrid_property.expression()</span></tt></a>. Below we illustrate the case where a conditional needs to be present inside the hybrid, using the <tt class="docutils literal"><span class="pre">if</span></tt> statement in Python and the <a class="reference internal" href="../core/sqlelement.html#sqlalchemy.sql.expression.case" title="sqlalchemy.sql.expression.case"><tt class="xref py py-func docutils literal"><span class="pre">sql.expression.case()</span></tt></a> construct for SQL expressions:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy.ext.hybrid</span> <span class="kn">import</span> <span class="n">hybrid_property</span> <span class="kn">from</span> <span class="nn">sqlalchemy.sql</span> <span class="kn">import</span> <span class="n">case</span> <span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'user'</span> <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> <span class="n">firstname</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> <span class="n">lastname</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> <span class="nd">@hybrid_property</span> <span class="k">def</span> <span class="nf">fullname</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">firstname</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">firstname</span> <span class="o">+</span> <span class="s">" "</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">lastname</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">lastname</span> <span class="nd">@fullname.expression</span> <span class="k">def</span> <span class="nf">fullname</span><span class="p">(</span><span class="n">cls</span><span class="p">):</span> <span class="k">return</span> <span class="n">case</span><span class="p">([</span> <span class="p">(</span><span class="n">cls</span><span class="o">.</span><span class="n">firstname</span> <span class="o">!=</span> <span class="bp">None</span><span class="p">,</span> <span class="n">cls</span><span class="o">.</span><span class="n">firstname</span> <span class="o">+</span> <span class="s">" "</span> <span class="o">+</span> <span class="n">cls</span><span class="o">.</span><span class="n">lastname</span><span class="p">),</span> <span class="p">],</span> <span class="n">else_</span> <span class="o">=</span> <span class="n">cls</span><span class="o">.</span><span class="n">lastname</span><span class="p">)</span></pre></div> </div> </div> <div class="section" id="using-column-property"> <span id="mapper-column-property-sql-expressions"></span><h3>Using column_property<a class="headerlink" href="#using-column-property" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">orm.column_property()</span></tt></a> function can be used to map a SQL expression in a manner similar to a regularly mapped <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a>. With this technique, the attribute is loaded along with all other column-mapped attributes at load time. This is in some cases an advantage over the usage of hybrids, as the value can be loaded up front at the same time as the parent row of the object, particularly if the expression is one which links to other tables (typically as a correlated subquery) to access data that wouldn’t normally be available on an already loaded object.</p> <p>Disadvantages to using <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">orm.column_property()</span></tt></a> for SQL expressions include that the expression must be compatible with the SELECT statement emitted for the class as a whole, and there are also some configurational quirks which can occur when using <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">orm.column_property()</span></tt></a> from declarative mixins.</p> <p>Our “fullname” example can be expressed using <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">orm.column_property()</span></tt></a> as follows:</p> <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">column_property</span> <span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'user'</span> <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> <span class="n">firstname</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> <span class="n">lastname</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> <span class="n">fullname</span> <span class="o">=</span> <span class="n">column_property</span><span class="p">(</span><span class="n">firstname</span> <span class="o">+</span> <span class="s">" "</span> <span class="o">+</span> <span class="n">lastname</span><span class="p">)</span></pre></div> </div> <p>Correlated subqueries may be used as well. Below we use the <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.select" title="sqlalchemy.sql.expression.select"><tt class="xref py py-func docutils literal"><span class="pre">select()</span></tt></a> construct to create a SELECT that links together the count of <tt class="docutils literal"><span class="pre">Address</span></tt> objects available for a particular <tt class="docutils literal"><span class="pre">User</span></tt>:</p> <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">column_property</span> <span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">select</span><span class="p">,</span> <span class="n">func</span> <span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">Column</span><span class="p">,</span> <span class="n">Integer</span><span class="p">,</span> <span class="n">String</span><span class="p">,</span> <span class="n">ForeignKey</span> <span class="kn">from</span> <span class="nn">sqlalchemy.ext.declarative</span> <span class="kn">import</span> <span class="n">declarative_base</span> <span class="n">Base</span> <span class="o">=</span> <span class="n">declarative_base</span><span class="p">()</span> <span class="k">class</span> <span class="nc">Address</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'address'</span> <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> <span class="n">user_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">'user.id'</span><span class="p">))</span> <span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'user'</span> <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> <span class="n">address_count</span> <span class="o">=</span> <span class="n">column_property</span><span class="p">(</span> <span class="n">select</span><span class="p">([</span><span class="n">func</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="n">Address</span><span class="o">.</span><span class="n">id</span><span class="p">)])</span><span class="o">.</span>\ <span class="n">where</span><span class="p">(</span><span class="n">Address</span><span class="o">.</span><span class="n">user_id</span><span class="o">==</span><span class="nb">id</span><span class="p">)</span><span class="o">.</span>\ <span class="n">correlate_except</span><span class="p">(</span><span class="n">Address</span><span class="p">)</span> <span class="p">)</span></pre></div> </div> <p>In the above example, we define a <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.select" title="sqlalchemy.sql.expression.select"><tt class="xref py py-func docutils literal"><span class="pre">select()</span></tt></a> construct like the following:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">select</span><span class="p">([</span><span class="n">func</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="n">Address</span><span class="o">.</span><span class="n">id</span><span class="p">)])</span><span class="o">.</span>\ <span class="n">where</span><span class="p">(</span><span class="n">Address</span><span class="o">.</span><span class="n">user_id</span><span class="o">==</span><span class="nb">id</span><span class="p">)</span><span class="o">.</span>\ <span class="n">correlate_except</span><span class="p">(</span><span class="n">Address</span><span class="p">)</span></pre></div> </div> <p>The meaning of the above statement is, select the count of <tt class="docutils literal"><span class="pre">Address.id</span></tt> rows where the <tt class="docutils literal"><span class="pre">Address.user_id</span></tt> column is equated to <tt class="docutils literal"><span class="pre">id</span></tt>, which in the context of the <tt class="docutils literal"><span class="pre">User</span></tt> class is the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> named <tt class="docutils literal"><span class="pre">id</span></tt> (note that <tt class="docutils literal"><span class="pre">id</span></tt> is also the name of a Python built in function, which is not what we want to use here - if we were outside of the <tt class="docutils literal"><span class="pre">User</span></tt> class definition, we’d use <tt class="docutils literal"><span class="pre">User.id</span></tt>).</p> <p>The <tt class="xref py py-meth docutils literal"><span class="pre">select.correlate_except()</span></tt> directive indicates that each element in the FROM clause of this <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.select" title="sqlalchemy.sql.expression.select"><tt class="xref py py-func docutils literal"><span class="pre">select()</span></tt></a> may be omitted from the FROM list (that is, correlated to the enclosing SELECT statement against <tt class="docutils literal"><span class="pre">User</span></tt>) except for the one corresponding to <tt class="docutils literal"><span class="pre">Address</span></tt>. This isn’t strictly necessary, but prevents <tt class="docutils literal"><span class="pre">Address</span></tt> from being inadvertently omitted from the FROM list in the case of a long string of joins between <tt class="docutils literal"><span class="pre">User</span></tt> and <tt class="docutils literal"><span class="pre">Address</span></tt> tables where SELECT statements against <tt class="docutils literal"><span class="pre">Address</span></tt> are nested.</p> <p>If import issues prevent the <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">column_property()</span></tt></a> from being defined inline with the class, it can be assigned to the class after both are configured. In Declarative this has the effect of calling <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.add_property" title="sqlalchemy.orm.mapper.Mapper.add_property"><tt class="xref py py-meth docutils literal"><span class="pre">Mapper.add_property()</span></tt></a> to add an additional property after the fact:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">User</span><span class="o">.</span><span class="n">address_count</span> <span class="o">=</span> <span class="n">column_property</span><span class="p">(</span> <span class="n">select</span><span class="p">([</span><span class="n">func</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="n">Address</span><span class="o">.</span><span class="n">id</span><span class="p">)])</span><span class="o">.</span>\ <span class="n">where</span><span class="p">(</span><span class="n">Address</span><span class="o">.</span><span class="n">user_id</span><span class="o">==</span><span class="n">User</span><span class="o">.</span><span class="n">id</span><span class="p">)</span> <span class="p">)</span></pre></div> </div> <p>For many-to-many relationships, use <a class="reference internal" href="../core/sqlelement.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> to join the fields of the association table to both tables in a relation, illustrated here with a classical mapping:</p> <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">and_</span> <span class="n">mapper</span><span class="p">(</span><span class="n">Author</span><span class="p">,</span> <span class="n">authors</span><span class="p">,</span> <span class="n">properties</span><span class="o">=</span><span class="p">{</span> <span class="s">'book_count'</span><span class="p">:</span> <span class="n">column_property</span><span class="p">(</span> <span class="n">select</span><span class="p">([</span><span class="n">func</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="n">books</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="p">)],</span> <span class="n">and_</span><span class="p">(</span> <span class="n">book_authors</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">author_id</span><span class="o">==</span><span class="n">authors</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="p">,</span> <span class="n">book_authors</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">book_id</span><span class="o">==</span><span class="n">books</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span> <span class="p">)))</span> <span class="p">})</span></pre></div> </div> </div> <div class="section" id="using-a-plain-descriptor"> <h3>Using a plain descriptor<a class="headerlink" href="#using-a-plain-descriptor" title="Permalink to this headline">¶</a></h3> <p>In cases where a SQL query more elaborate than what <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">orm.column_property()</span></tt></a> or <a class="reference internal" href="extensions/hybrid.html#sqlalchemy.ext.hybrid.hybrid_property" title="sqlalchemy.ext.hybrid.hybrid_property"><tt class="xref py py-class docutils literal"><span class="pre">hybrid_property</span></tt></a> can provide must be emitted, a regular Python function accessed as an attribute can be used, assuming the expression only needs to be available on an already-loaded instance. The function is decorated with Python’s own <tt class="docutils literal"><span class="pre">@property</span></tt> decorator to mark it as a read-only attribute. Within the function, <a class="reference internal" href="session.html#sqlalchemy.orm.session.object_session" title="sqlalchemy.orm.session.object_session"><tt class="xref py py-func docutils literal"><span class="pre">object_session()</span></tt></a> is used to locate the <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> corresponding to the current object, which is then used to emit a query:</p> <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">object_session</span> <span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">select</span><span class="p">,</span> <span class="n">func</span> <span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'user'</span> <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> <span class="n">firstname</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> <span class="n">lastname</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> <span class="nd">@property</span> <span class="k">def</span> <span class="nf">address_count</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="n">object_session</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span><span class="o">.</span>\ <span class="n">scalar</span><span class="p">(</span> <span class="n">select</span><span class="p">([</span><span class="n">func</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="n">Address</span><span class="o">.</span><span class="n">id</span><span class="p">)])</span><span class="o">.</span>\ <span class="n">where</span><span class="p">(</span><span class="n">Address</span><span class="o">.</span><span class="n">user_id</span><span class="o">==</span><span class="bp">self</span><span class="o">.</span><span class="n">id</span><span class="p">)</span> <span class="p">)</span></pre></div> </div> <p>The plain descriptor approach is useful as a last resort, but is less performant in the usual case than both the hybrid and column property approaches, in that it needs to emit a SQL query upon each access.</p> </div> </div> <div class="section" id="changing-attribute-behavior"> <h2>Changing Attribute Behavior<a class="headerlink" href="#changing-attribute-behavior" title="Permalink to this headline">¶</a></h2> <div class="section" id="simple-validators"> <span id="id1"></span><h3>Simple Validators<a class="headerlink" href="#simple-validators" title="Permalink to this headline">¶</a></h3> <p>A quick way to add a “validation” routine to an attribute is to use the <a class="reference internal" href="#sqlalchemy.orm.validates" title="sqlalchemy.orm.validates"><tt class="xref py py-func docutils literal"><span class="pre">validates()</span></tt></a> decorator. An attribute validator can raise an exception, halting the process of mutating the attribute’s value, or can change the given value into something different. Validators, like all attribute extensions, are only called by normal userland code; they are not issued when the ORM is populating the object:</p> <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">validates</span> <span class="k">class</span> <span class="nc">EmailAddress</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'address'</span> <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> <span class="n">email</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="nd">@validates</span><span class="p">(</span><span class="s">'email'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">validate_email</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">address</span><span class="p">):</span> <span class="k">assert</span> <span class="s">'@'</span> <span class="ow">in</span> <span class="n">address</span> <span class="k">return</span> <span class="n">address</span></pre></div> </div> <p>Validators also receive collection events, when items are added to a collection:</p> <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">validates</span> <span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="c"># ...</span> <span class="n">addresses</span> <span class="o">=</span> <span class="n">relationship</span><span class="p">(</span><span class="s">"Address"</span><span class="p">)</span> <span class="nd">@validates</span><span class="p">(</span><span class="s">'addresses'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">validate_address</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">address</span><span class="p">):</span> <span class="k">assert</span> <span class="s">'@'</span> <span class="ow">in</span> <span class="n">address</span><span class="o">.</span><span class="n">email</span> <span class="k">return</span> <span class="n">address</span></pre></div> </div> <p>Note that the <a class="reference internal" href="#sqlalchemy.orm.validates" title="sqlalchemy.orm.validates"><tt class="xref py py-func docutils literal"><span class="pre">validates()</span></tt></a> decorator is a convenience function built on top of attribute events. An application that requires more control over configuration of attribute change behavior can make use of this system, described at <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>.</p> <dl class="function"> <dt id="sqlalchemy.orm.validates"> <tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">validates</tt><big>(</big><em>*names</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.validates" title="Permalink to this definition">¶</a></dt> <dd><p>Decorate a method as a ‘validator’ for one or more named properties.</p> <p>Designates a method as a validator, a method which receives the name of the attribute as well as a value to be assigned, or in the case of a collection, the value to be added to the collection. The function can then raise validation exceptions to halt the process from continuing (where Python’s built-in <tt class="docutils literal"><span class="pre">ValueError</span></tt> and <tt class="docutils literal"><span class="pre">AssertionError</span></tt> exceptions are reasonable choices), or can modify or replace the value before proceeding. The function should otherwise return the given value.</p> <p>Note that a validator for a collection <strong>cannot</strong> issue a load of that collection within the validation routine - this usage raises an assertion to avoid recursion overflows. This is a reentrant condition which is not supported.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><span class="target" id="sqlalchemy.orm.validates.params.*names"></span><strong>*names</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.validates.params.*names">¶</a> – list of attribute names to be validated.</li> <li><span class="target" id="sqlalchemy.orm.validates.params.include_removes"></span><strong>include_removes</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.validates.params.include_removes">¶</a> – <p>if True, “remove” events will be sent as well - the validation function must accept an additional argument “is_remove” which will be a boolean.</p> <div class="versionadded"> <p><span>New in version 0.7.7.</span></p> </div> </li> </ul> </td> </tr> </tbody> </table> </dd></dl> </div> <div class="section" id="using-descriptors-and-hybrids"> <span id="synonyms"></span><h3>Using Descriptors and Hybrids<a class="headerlink" href="#using-descriptors-and-hybrids" title="Permalink to this headline">¶</a></h3> <p>A more comprehensive way to produce modified behavior for an attribute is to use descriptors. These are commonly used in Python using the <tt class="docutils literal"><span class="pre">property()</span></tt> function. The standard SQLAlchemy technique for descriptors is to create a plain descriptor, and to have it read/write from a mapped attribute with a different name. Below we illustrate this using Python 2.6-style properties:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">EmailAddress</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'email_address'</span> <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> <span class="c"># name the attribute with an underscore,</span> <span class="c"># different from the column name</span> <span class="n">_email</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="s">"email"</span><span class="p">,</span> <span class="n">String</span><span class="p">)</span> <span class="c"># then create an ".email" attribute</span> <span class="c"># to get/set "._email"</span> <span class="nd">@property</span> <span class="k">def</span> <span class="nf">email</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_email</span> <span class="nd">@email.setter</span> <span class="k">def</span> <span class="nf">email</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">email</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">_email</span> <span class="o">=</span> <span class="n">email</span></pre></div> </div> <p>The approach above will work, but there’s more we can add. While our <tt class="docutils literal"><span class="pre">EmailAddress</span></tt> object will shuttle the value through the <tt class="docutils literal"><span class="pre">email</span></tt> descriptor and into the <tt class="docutils literal"><span class="pre">_email</span></tt> mapped attribute, the class level <tt class="docutils literal"><span class="pre">EmailAddress.email</span></tt> attribute does not have the usual expression semantics usable with <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>. To provide these, we instead use the <a class="reference internal" href="extensions/hybrid.html#module-sqlalchemy.ext.hybrid" title="sqlalchemy.ext.hybrid"><tt class="xref py py-mod docutils literal"><span class="pre">hybrid</span></tt></a> extension as follows:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy.ext.hybrid</span> <span class="kn">import</span> <span class="n">hybrid_property</span> <span class="k">class</span> <span class="nc">EmailAddress</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'email_address'</span> <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> <span class="n">_email</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="s">"email"</span><span class="p">,</span> <span class="n">String</span><span class="p">)</span> <span class="nd">@hybrid_property</span> <span class="k">def</span> <span class="nf">email</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_email</span> <span class="nd">@email.setter</span> <span class="k">def</span> <span class="nf">email</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">email</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">_email</span> <span class="o">=</span> <span class="n">email</span></pre></div> </div> <p>The <tt class="docutils literal"><span class="pre">.email</span></tt> attribute, in addition to providing getter/setter behavior when we have an instance of <tt class="docutils literal"><span class="pre">EmailAddress</span></tt>, also provides a SQL expression when used at the class level, that is, from the <tt class="docutils literal"><span class="pre">EmailAddress</span></tt> class directly:</p> <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">Session</span> <span class="n">session</span> <span class="o">=</span> <span class="n">Session</span><span class="p">()</span> <a href='#' class='sql_link'>sql</a><span class="n">address</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">EmailAddress</span><span class="p">)</span><span class="o">.</span>\ <span class="nb">filter</span><span class="p">(</span><span class="n">EmailAddress</span><span class="o">.</span><span class="n">email</span> <span class="o">==</span> <span class="s">'address@example.com'</span><span class="p">)</span><span class="o">.</span>\ <span class="n">one</span><span class="p">()</span> <div class='popup_sql'>SELECT address.email AS address_email, address.id AS address_id FROM address WHERE address.email = ? ('address@example.com',)</div> <span class="n">address</span><span class="o">.</span><span class="n">email</span> <span class="o">=</span> <span class="s">'otheraddress@example.com'</span> <a href='#' class='sql_link'>sql</a><span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span> <div class='popup_sql'>UPDATE address SET email=? WHERE address.id = ? ('otheraddress@example.com', 1) COMMIT</div></pre></div> </div> <p>The <a class="reference internal" href="extensions/hybrid.html#sqlalchemy.ext.hybrid.hybrid_property" title="sqlalchemy.ext.hybrid.hybrid_property"><tt class="xref py py-class docutils literal"><span class="pre">hybrid_property</span></tt></a> also allows us to change the behavior of the attribute, including defining separate behaviors when the attribute is accessed at the instance level versus at the class/expression level, using the <a class="reference internal" href="extensions/hybrid.html#sqlalchemy.ext.hybrid.hybrid_property.expression" title="sqlalchemy.ext.hybrid.hybrid_property.expression"><tt class="xref py py-meth docutils literal"><span class="pre">hybrid_property.expression()</span></tt></a> modifier. Such as, if we wanted to add a host name automatically, we might define two sets of string manipulation logic:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">EmailAddress</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'email_address'</span> <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> <span class="n">_email</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="s">"email"</span><span class="p">,</span> <span class="n">String</span><span class="p">)</span> <span class="nd">@hybrid_property</span> <span class="k">def</span> <span class="nf">email</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">"""Return the value of _email up until the last twelve</span> <span class="sd"> characters."""</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_email</span><span class="p">[:</span><span class="o">-</span><span class="mi">12</span><span class="p">]</span> <span class="nd">@email.setter</span> <span class="k">def</span> <span class="nf">email</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">email</span><span class="p">):</span> <span class="sd">"""Set the value of _email, tacking on the twelve character</span> <span class="sd"> value @example.com."""</span> <span class="bp">self</span><span class="o">.</span><span class="n">_email</span> <span class="o">=</span> <span class="n">email</span> <span class="o">+</span> <span class="s">"@example.com"</span> <span class="nd">@email.expression</span> <span class="k">def</span> <span class="nf">email</span><span class="p">(</span><span class="n">cls</span><span class="p">):</span> <span class="sd">"""Produce a SQL expression that represents the value</span> <span class="sd"> of the _email column, minus the last twelve characters."""</span> <span class="k">return</span> <span class="n">func</span><span class="o">.</span><span class="n">substr</span><span class="p">(</span><span class="n">cls</span><span class="o">.</span><span class="n">_email</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">func</span><span class="o">.</span><span class="n">length</span><span class="p">(</span><span class="n">cls</span><span class="o">.</span><span class="n">_email</span><span class="p">)</span> <span class="o">-</span> <span class="mi">12</span><span class="p">)</span></pre></div> </div> <p>Above, accessing the <tt class="docutils literal"><span class="pre">email</span></tt> property of an instance of <tt class="docutils literal"><span class="pre">EmailAddress</span></tt> will return the value of the <tt class="docutils literal"><span class="pre">_email</span></tt> attribute, removing or adding the hostname <tt class="docutils literal"><span class="pre">@example.com</span></tt> from the value. When we query against the <tt class="docutils literal"><span class="pre">email</span></tt> attribute, a SQL function is rendered which produces the same effect:</p> <div class="highlight-python+sql"><div class="highlight"><pre><a href='#' class='sql_link'>sql</a><span class="n">address</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">EmailAddress</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">EmailAddress</span><span class="o">.</span><span class="n">email</span> <span class="o">==</span> <span class="s">'address'</span><span class="p">)</span><span class="o">.</span><span class="n">one</span><span class="p">()</span> <div class='popup_sql'>SELECT address.email AS address_email, address.id AS address_id FROM address WHERE substr(address.email, ?, length(address.email) - ?) = ? (0, 12, 'address')</div></pre></div> </div> <p>Read more about Hybrids at <a class="reference internal" href="extensions/hybrid.html"><em>Hybrid Attributes</em></a>.</p> </div> <div class="section" id="id2"> <h3>Synonyms<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h3> <p>Synonyms are a mapper-level construct that applies expression behavior to a descriptor based attribute.</p> <div class="versionchanged"> <p><span>Changed in version 0.7: </span>The functionality of synonym is superceded as of 0.7 by hybrid attributes.</p> </div> <dl class="function"> <dt id="sqlalchemy.orm.synonym"> <tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">synonym</tt><big>(</big><em>name</em>, <em>map_column=False</em>, <em>descriptor=None</em>, <em>comparator_factory=None</em>, <em>doc=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.synonym" title="Permalink to this definition">¶</a></dt> <dd><p>Denote an attribute name as a synonym to a mapped property.</p> <div class="versionchanged"> <p><span>Changed in version 0.7: </span><a class="reference internal" href="#sqlalchemy.orm.synonym" title="sqlalchemy.orm.synonym"><tt class="xref py py-func docutils literal"><span class="pre">synonym()</span></tt></a> is superseded by the <a class="reference internal" href="extensions/hybrid.html#module-sqlalchemy.ext.hybrid" title="sqlalchemy.ext.hybrid"><tt class="xref py py-mod docutils literal"><span class="pre">hybrid</span></tt></a> extension. See the documentation for hybrids at <a class="reference internal" href="extensions/hybrid.html"><em>Hybrid Attributes</em></a>.</p> </div> <p>Used with the <tt class="docutils literal"><span class="pre">properties</span></tt> dictionary sent to <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">MyClass</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">def</span> <span class="nf">_get_status</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_status</span> <span class="k">def</span> <span class="nf">_set_status</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">_status</span> <span class="o">=</span> <span class="n">value</span> <span class="n">status</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">_get_status</span><span class="p">,</span> <span class="n">_set_status</span><span class="p">)</span> <span class="n">mapper</span><span class="p">(</span><span class="n">MyClass</span><span class="p">,</span> <span class="n">sometable</span><span class="p">,</span> <span class="n">properties</span><span class="o">=</span><span class="p">{</span> <span class="s">"status"</span><span class="p">:</span><span class="n">synonym</span><span class="p">(</span><span class="s">"_status"</span><span class="p">,</span> <span class="n">map_column</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="p">})</span></pre></div> </div> <p>Above, the <tt class="docutils literal"><span class="pre">status</span></tt> attribute of MyClass will produce expression behavior against the table column named <tt class="docutils literal"><span class="pre">status</span></tt>, using the Python attribute <tt class="docutils literal"><span class="pre">_status</span></tt> on the mapped class to represent the underlying value.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><span class="target" id="sqlalchemy.orm.synonym.params.name"></span><strong>name</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.synonym.params.name">¶</a> – the name of the existing mapped property, which can be any other <tt class="docutils literal"><span class="pre">MapperProperty</span></tt> including column-based properties and relationships.</li> <li><span class="target" id="sqlalchemy.orm.synonym.params.map_column"></span><strong>map_column</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.synonym.params.map_column">¶</a> – if <tt class="docutils literal"><span class="pre">True</span></tt>, an additional <tt class="docutils literal"><span class="pre">ColumnProperty</span></tt> is created on the mapper automatically, using the synonym’s name as the keyname of the property, and the keyname of this <tt class="docutils literal"><span class="pre">synonym()</span></tt> as the name of the column to map.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> </div> <div class="section" id="operator-customization"> <span id="custom-comparators"></span><h3>Operator Customization<a class="headerlink" href="#operator-customization" title="Permalink to this headline">¶</a></h3> <p>The “operators” used by the SQLAlchemy ORM and Core expression language are fully customizable. For example, the comparison expression <tt class="docutils literal"><span class="pre">User.name</span> <span class="pre">==</span> <span class="pre">'ed'</span></tt> makes usage of an operator built into Python itself called <tt class="docutils literal"><span class="pre">operator.eq</span></tt> - the actual SQL construct which SQLAlchemy associates with such an operator can be modified. New operations can be associated with column expressions as well. The operators which take place for column expressions are most directly redefined at the type level - see the section <a class="reference internal" href="../core/types.html#types-operators"><em>Redefining and Creating New Operators</em></a> for a description.</p> <p>ORM level functions like <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">column_property()</span></tt></a>, <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a>, and <a class="reference internal" href="#sqlalchemy.orm.composite" title="sqlalchemy.orm.composite"><tt class="xref py py-func docutils literal"><span class="pre">composite()</span></tt></a> also provide for operator redefinition at the ORM level, by passing a <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces.PropComparator" title="sqlalchemy.orm.interfaces.PropComparator"><tt class="xref py py-class docutils literal"><span class="pre">PropComparator</span></tt></a> subclass to the <tt class="docutils literal"><span class="pre">comparator_factory</span></tt> argument of each function. Customization of operators at this level is a rare use case. See the documentation at <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces.PropComparator" title="sqlalchemy.orm.interfaces.PropComparator"><tt class="xref py py-class docutils literal"><span class="pre">PropComparator</span></tt></a> for an overview.</p> </div> </div> <div class="section" id="composite-column-types"> <span id="mapper-composite"></span><h2>Composite Column Types<a class="headerlink" href="#composite-column-types" title="Permalink to this headline">¶</a></h2> <p>Sets of columns can be associated with a single user-defined datatype. The ORM provides a single attribute which represents the group of columns using the class you provide.</p> <div class="versionchanged"> <p><span>Changed in version 0.7: </span>Composites have been simplified such that they no longer “conceal” the underlying column based attributes. Additionally, in-place mutation is no longer automatic; see the section below on enabling mutability to support tracking of in-place changes.</p> </div> <p>A simple example represents pairs of columns as a <tt class="docutils literal"><span class="pre">Point</span></tt> object. <tt class="docutils literal"><span class="pre">Point</span></tt> represents such a pair as <tt class="docutils literal"><span class="pre">.x</span></tt> and <tt class="docutils literal"><span class="pre">.y</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">=</span> <span class="n">y</span> <span class="k">def</span> <span class="nf">__composite_values__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="s">"Point(x=</span><span class="si">%r</span><span class="s">, y=</span><span class="si">%r</span><span class="s">)"</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span><span class="p">)</span> <span class="k">def</span> <span class="nf">__eq__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="k">return</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="n">Point</span><span class="p">)</span> <span class="ow">and</span> \ <span class="n">other</span><span class="o">.</span><span class="n">x</span> <span class="o">==</span> <span class="bp">self</span><span class="o">.</span><span class="n">x</span> <span class="ow">and</span> \ <span class="n">other</span><span class="o">.</span><span class="n">y</span> <span class="o">==</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="k">def</span> <span class="nf">__ne__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="k">return</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">__eq__</span><span class="p">(</span><span class="n">other</span><span class="p">)</span></pre></div> </div> <p>The requirements for the custom datatype class are that it have a constructor which accepts positional arguments corresponding to its column format, and also provides a method <tt class="docutils literal"><span class="pre">__composite_values__()</span></tt> which returns the state of the object as a list or tuple, in order of its column-based attributes. It also should supply adequate <tt class="docutils literal"><span class="pre">__eq__()</span></tt> and <tt class="docutils literal"><span class="pre">__ne__()</span></tt> methods which test the equality of two instances.</p> <p>We will create a mapping to a table <tt class="docutils literal"><span class="pre">vertice</span></tt>, which represents two points as <tt class="docutils literal"><span class="pre">x1/y1</span></tt> and <tt class="docutils literal"><span class="pre">x2/y2</span></tt>. These are created normally as <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> objects. Then, the <a class="reference internal" href="#sqlalchemy.orm.composite" title="sqlalchemy.orm.composite"><tt class="xref py py-func docutils literal"><span class="pre">composite()</span></tt></a> function is used to assign new attributes that will represent sets of columns via the <tt class="docutils literal"><span class="pre">Point</span></tt> class:</p> <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">Column</span><span class="p">,</span> <span class="n">Integer</span> <span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">composite</span> <span class="kn">from</span> <span class="nn">sqlalchemy.ext.declarative</span> <span class="kn">import</span> <span class="n">declarative_base</span> <span class="n">Base</span> <span class="o">=</span> <span class="n">declarative_base</span><span class="p">()</span> <span class="k">class</span> <span class="nc">Vertex</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'vertice'</span> <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> <span class="n">x1</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">y1</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">x2</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">y2</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">start</span> <span class="o">=</span> <span class="n">composite</span><span class="p">(</span><span class="n">Point</span><span class="p">,</span> <span class="n">x1</span><span class="p">,</span> <span class="n">y1</span><span class="p">)</span> <span class="n">end</span> <span class="o">=</span> <span class="n">composite</span><span class="p">(</span><span class="n">Point</span><span class="p">,</span> <span class="n">x2</span><span class="p">,</span> <span class="n">y2</span><span class="p">)</span></pre></div> </div> <p>A classical mapping above would define each <a class="reference internal" href="#sqlalchemy.orm.composite" title="sqlalchemy.orm.composite"><tt class="xref py py-func docutils literal"><span class="pre">composite()</span></tt></a> against the existing table:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">mapper</span><span class="p">(</span><span class="n">Vertex</span><span class="p">,</span> <span class="n">vertice_table</span><span class="p">,</span> <span class="n">properties</span><span class="o">=</span><span class="p">{</span> <span class="s">'start'</span><span class="p">:</span><span class="n">composite</span><span class="p">(</span><span class="n">Point</span><span class="p">,</span> <span class="n">vertice_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">x1</span><span class="p">,</span> <span class="n">vertice_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">y1</span><span class="p">),</span> <span class="s">'end'</span><span class="p">:</span><span class="n">composite</span><span class="p">(</span><span class="n">Point</span><span class="p">,</span> <span class="n">vertice_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">x2</span><span class="p">,</span> <span class="n">vertice_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">y2</span><span class="p">),</span> <span class="p">})</span></pre></div> </div> <p>We can now persist and use <tt class="docutils literal"><span class="pre">Vertex</span></tt> instances, as well as query for them, using the <tt class="docutils literal"><span class="pre">.start</span></tt> and <tt class="docutils literal"><span class="pre">.end</span></tt> attributes against ad-hoc <tt class="docutils literal"><span class="pre">Point</span></tt> instances:</p> <div class="highlight-python+sql"><div class="highlight"><pre><span class="o">>>></span> <span class="n">v</span> <span class="o">=</span> <span class="n">Vertex</span><span class="p">(</span><span class="n">start</span><span class="o">=</span><span class="n">Point</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="n">end</span><span class="o">=</span><span class="n">Point</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">))</span> <span class="o">>>></span> <span class="n">session</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="o">>>></span> <span class="n">q</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">Vertex</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">Vertex</span><span class="o">.</span><span class="n">start</span> <span class="o">==</span> <span class="n">Point</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">))</span> <a href='#' class='sql_link'>sql</a><span class="o">>>></span> <span class="k">print</span> <span class="n">q</span><span class="o">.</span><span class="n">first</span><span class="p">()</span><span class="o">.</span><span class="n">start</span> <div class='popup_sql'>BEGIN (implicit) INSERT INTO vertice (x1, y1, x2, y2) VALUES (?, ?, ?, ?) (3, 4, 5, 6) SELECT vertice.id AS vertice_id, vertice.x1 AS vertice_x1, vertice.y1 AS vertice_y1, vertice.x2 AS vertice_x2, vertice.y2 AS vertice_y2 FROM vertice WHERE vertice.x1 = ? AND vertice.y1 = ? LIMIT ? OFFSET ? (3, 4, 1, 0)</div><span class="n">Point</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span></pre></div> </div> <dl class="function"> <dt id="sqlalchemy.orm.composite"> <tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">composite</tt><big>(</big><em>class_</em>, <em>*cols</em>, <em>**kwargs</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.composite" title="Permalink to this definition">¶</a></dt> <dd><p>Return a composite column-based property for use with a Mapper.</p> <p>See the mapping documentation section <a class="reference internal" href="#mapper-composite"><em>Composite Column Types</em></a> for a full usage example.</p> <p>The <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces.MapperProperty" title="sqlalchemy.orm.interfaces.MapperProperty"><tt class="xref py py-class docutils literal"><span class="pre">MapperProperty</span></tt></a> returned by <a class="reference internal" href="#sqlalchemy.orm.composite" title="sqlalchemy.orm.composite"><tt class="xref py py-func docutils literal"><span class="pre">composite()</span></tt></a> is the <a class="reference internal" href="internals.html#sqlalchemy.orm.descriptor_props.CompositeProperty" title="sqlalchemy.orm.descriptor_props.CompositeProperty"><tt class="xref py py-class docutils literal"><span class="pre">CompositeProperty</span></tt></a>.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><span class="target" id="sqlalchemy.orm.composite.params.class_"></span><strong>class_</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.composite.params.class_">¶</a> – The “composite type” class.</li> <li><span class="target" id="sqlalchemy.orm.composite.params.*cols"></span><strong>*cols</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.composite.params.*cols">¶</a> – List of Column objects to be mapped.</li> <li><span class="target" id="sqlalchemy.orm.composite.params.active_history"></span><strong>active_history=False</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.composite.params.active_history">¶</a> – <p>When <tt class="docutils literal"><span class="pre">True</span></tt>, indicates that the “previous” value for a scalar attribute should be loaded when replaced, if not already loaded. See the same flag on <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">column_property()</span></tt></a>.</p> <div class="versionchanged"> <p><span>Changed in version 0.7: </span>This flag specifically becomes meaningful - previously it was a placeholder.</p> </div> </li> <li><span class="target" id="sqlalchemy.orm.composite.params.group"></span><strong>group</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.composite.params.group">¶</a> – A group name for this property when marked as deferred.</li> <li><span class="target" id="sqlalchemy.orm.composite.params.deferred"></span><strong>deferred</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.composite.params.deferred">¶</a> – When True, the column property is “deferred”, meaning that it does not load immediately, and is instead loaded when the attribute is first accessed on an instance. See also <a class="reference internal" href="#sqlalchemy.orm.deferred" title="sqlalchemy.orm.deferred"><tt class="xref py py-func docutils literal"><span class="pre">deferred()</span></tt></a>.</li> <li><span class="target" id="sqlalchemy.orm.composite.params.comparator_factory"></span><strong>comparator_factory</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.composite.params.comparator_factory">¶</a> – a class which extends <a class="reference internal" href="internals.html#sqlalchemy.orm.descriptor_props.CompositeProperty.Comparator" title="sqlalchemy.orm.descriptor_props.CompositeProperty.Comparator"><tt class="xref py py-class docutils literal"><span class="pre">CompositeProperty.Comparator</span></tt></a> which provides custom SQL clause generation for comparison operations.</li> <li><span class="target" id="sqlalchemy.orm.composite.params.doc"></span><strong>doc</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.composite.params.doc">¶</a> – optional string that will be applied as the doc on the class-bound descriptor.</li> <li><span class="target" id="sqlalchemy.orm.composite.params.info"></span><strong>info</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.composite.params.info">¶</a> – <p>Optional data dictionary which will be populated into the <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> <div class="versionadded"> <p><span>New in version 0.8.</span></p> </div> </li> <li><span class="target" id="sqlalchemy.orm.composite.params.extension"></span><strong>extension</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.composite.params.extension">¶</a> – an <a class="reference internal" href="deprecated.html#sqlalchemy.orm.interfaces.AttributeExtension" title="sqlalchemy.orm.interfaces.AttributeExtension"><tt class="xref py py-class docutils literal"><span class="pre">AttributeExtension</span></tt></a> instance, or list of extensions, which will be prepended to the list of attribute listeners for the resulting descriptor placed on the class. <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> </ul> </td> </tr> </tbody> </table> </dd></dl> <div class="section" id="tracking-in-place-mutations-on-composites"> <h3>Tracking In-Place Mutations on Composites<a class="headerlink" href="#tracking-in-place-mutations-on-composites" title="Permalink to this headline">¶</a></h3> <p>In-place changes to an existing composite value are not tracked automatically. Instead, the composite class needs to provide events to its parent object explicitly. This task is largely automated via the usage of the <a class="reference internal" href="extensions/mutable.html#sqlalchemy.ext.mutable.MutableComposite" title="sqlalchemy.ext.mutable.MutableComposite"><tt class="xref py py-class docutils literal"><span class="pre">MutableComposite</span></tt></a> mixin, which uses events to associate each user-defined composite object with all parent associations. Please see the example in <a class="reference internal" href="extensions/mutable.html#mutable-composites"><em>Establishing Mutability on Composites</em></a>.</p> <div class="versionchanged"> <p><span>Changed in version 0.7: </span>In-place changes to an existing composite value are no longer tracked automatically; the functionality is superseded by the <a class="reference internal" href="extensions/mutable.html#sqlalchemy.ext.mutable.MutableComposite" title="sqlalchemy.ext.mutable.MutableComposite"><tt class="xref py py-class docutils literal"><span class="pre">MutableComposite</span></tt></a> class.</p> </div> </div> <div class="section" id="redefining-comparison-operations-for-composites"> <span id="composite-operations"></span><h3>Redefining Comparison Operations for Composites<a class="headerlink" href="#redefining-comparison-operations-for-composites" title="Permalink to this headline">¶</a></h3> <p>The “equals” comparison operation by default produces an AND of all corresponding columns equated to one another. This can be changed using the <tt class="docutils literal"><span class="pre">comparator_factory</span></tt> argument to <a class="reference internal" href="#sqlalchemy.orm.composite" title="sqlalchemy.orm.composite"><tt class="xref py py-func docutils literal"><span class="pre">composite()</span></tt></a>, where we specify a custom <a class="reference internal" href="internals.html#sqlalchemy.orm.descriptor_props.CompositeProperty.Comparator" title="sqlalchemy.orm.descriptor_props.CompositeProperty.Comparator"><tt class="xref py py-class docutils literal"><span class="pre">CompositeProperty.Comparator</span></tt></a> class to define existing or new operations. Below we illustrate the “greater than” operator, implementing the same expression that the base “greater than” does:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy.orm.properties</span> <span class="kn">import</span> <span class="n">CompositeProperty</span> <span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">sql</span> <span class="k">class</span> <span class="nc">PointComparator</span><span class="p">(</span><span class="n">CompositeProperty</span><span class="o">.</span><span class="n">Comparator</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__gt__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="sd">"""redefine the 'greater than' operation"""</span> <span class="k">return</span> <span class="n">sql</span><span class="o">.</span><span class="n">and_</span><span class="p">(</span><span class="o">*</span><span class="p">[</span><span class="n">a</span><span class="o">></span><span class="n">b</span> <span class="k">for</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">__clause_element__</span><span class="p">()</span><span class="o">.</span><span class="n">clauses</span><span class="p">,</span> <span class="n">other</span><span class="o">.</span><span class="n">__composite_values__</span><span class="p">())])</span> <span class="k">class</span> <span class="nc">Vertex</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">___tablename__</span> <span class="o">=</span> <span class="s">'vertice'</span> <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> <span class="n">x1</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">y1</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">x2</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">y2</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">start</span> <span class="o">=</span> <span class="n">composite</span><span class="p">(</span><span class="n">Point</span><span class="p">,</span> <span class="n">x1</span><span class="p">,</span> <span class="n">y1</span><span class="p">,</span> <span class="n">comparator_factory</span><span class="o">=</span><span class="n">PointComparator</span><span class="p">)</span> <span class="n">end</span> <span class="o">=</span> <span class="n">composite</span><span class="p">(</span><span class="n">Point</span><span class="p">,</span> <span class="n">x2</span><span class="p">,</span> <span class="n">y2</span><span class="p">,</span> <span class="n">comparator_factory</span><span class="o">=</span><span class="n">PointComparator</span><span class="p">)</span></pre></div> </div> </div> </div> <div class="section" id="mapping-a-class-against-multiple-tables"> <span id="maptojoin"></span><h2>Mapping a Class against Multiple Tables<a class="headerlink" href="#mapping-a-class-against-multiple-tables" title="Permalink to this headline">¶</a></h2> <p>Mappers can be constructed against arbitrary relational units (called <em>selectables</em>) in addition to plain tables. For example, the <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.join" title="sqlalchemy.sql.expression.join"><tt class="xref py py-func docutils literal"><span class="pre">join()</span></tt></a> function creates a selectable unit comprised of multiple tables, complete with its own composite primary key, which can be mapped in the same way as a <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a>:</p> <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">Table</span><span class="p">,</span> <span class="n">Column</span><span class="p">,</span> <span class="n">Integer</span><span class="p">,</span> \ <span class="n">String</span><span class="p">,</span> <span class="n">MetaData</span><span class="p">,</span> <span class="n">join</span><span class="p">,</span> <span class="n">ForeignKey</span> <span class="kn">from</span> <span class="nn">sqlalchemy.ext.declarative</span> <span class="kn">import</span> <span class="n">declarative_base</span> <span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">column_property</span> <span class="n">metadata</span> <span class="o">=</span> <span class="n">MetaData</span><span class="p">()</span> <span class="c"># define two Table objects</span> <span class="n">user_table</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s">'user'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="n">Column</span><span class="p">(</span><span class="s">'id'</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> <span class="n">Column</span><span class="p">(</span><span class="s">'name'</span><span class="p">,</span> <span class="n">String</span><span class="p">),</span> <span class="p">)</span> <span class="n">address_table</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s">'address'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="n">Column</span><span class="p">(</span><span class="s">'id'</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> <span class="n">Column</span><span class="p">(</span><span class="s">'user_id'</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">'user.id'</span><span class="p">)),</span> <span class="n">Column</span><span class="p">(</span><span class="s">'email_address'</span><span class="p">,</span> <span class="n">String</span><span class="p">)</span> <span class="p">)</span> <span class="c"># define a join between them. This</span> <span class="c"># takes place across the user.id and address.user_id</span> <span class="c"># columns.</span> <span class="n">user_address_join</span> <span class="o">=</span> <span class="n">join</span><span class="p">(</span><span class="n">user_table</span><span class="p">,</span> <span class="n">address_table</span><span class="p">)</span> <span class="n">Base</span> <span class="o">=</span> <span class="n">declarative_base</span><span class="p">()</span> <span class="c"># map to it</span> <span class="k">class</span> <span class="nc">AddressUser</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__table__</span> <span class="o">=</span> <span class="n">user_address_join</span> <span class="nb">id</span> <span class="o">=</span> <span class="n">column_property</span><span class="p">(</span><span class="n">user_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="p">,</span> <span class="n">address_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> <span class="n">address_id</span> <span class="o">=</span> <span class="n">address_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span></pre></div> </div> <p>In the example above, the join expresses columns for both the <tt class="docutils literal"><span class="pre">user</span></tt> and the <tt class="docutils literal"><span class="pre">address</span></tt> table. The <tt class="docutils literal"><span class="pre">user.id</span></tt> and <tt class="docutils literal"><span class="pre">address.user_id</span></tt> columns are equated by foreign key, so in the mapping they are defined as one attribute, <tt class="docutils literal"><span class="pre">AddressUser.id</span></tt>, using <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">column_property()</span></tt></a> to indicate a specialized column mapping. Based on this part of the configuration, the mapping will copy new primary key values from <tt class="docutils literal"><span class="pre">user.id</span></tt> into the <tt class="docutils literal"><span class="pre">address.user_id</span></tt> column when a flush occurs.</p> <p>Additionally, the <tt class="docutils literal"><span class="pre">address.id</span></tt> column is mapped explicitly to an attribute named <tt class="docutils literal"><span class="pre">address_id</span></tt>. This is to <strong>disambiguate</strong> the mapping of the <tt class="docutils literal"><span class="pre">address.id</span></tt> column from the same-named <tt class="docutils literal"><span class="pre">AddressUser.id</span></tt> attribute, which here has been assigned to refer to the <tt class="docutils literal"><span class="pre">user</span></tt> table combined with the <tt class="docutils literal"><span class="pre">address.user_id</span></tt> foreign key.</p> <p>The natural primary key of the above mapping is the composite of <tt class="docutils literal"><span class="pre">(user.id,</span> <span class="pre">address.id)</span></tt>, as these are the primary key columns of the <tt class="docutils literal"><span class="pre">user</span></tt> and <tt class="docutils literal"><span class="pre">address</span></tt> table combined together. The identity of an <tt class="docutils literal"><span class="pre">AddressUser</span></tt> object will be in terms of these two values, and is represented from an <tt class="docutils literal"><span class="pre">AddressUser</span></tt> object as <tt class="docutils literal"><span class="pre">(AddressUser.id,</span> <span class="pre">AddressUser.address_id)</span></tt>.</p> </div> <div class="section" id="mapping-a-class-against-arbitrary-selects"> <h2>Mapping a Class against Arbitrary Selects<a class="headerlink" href="#mapping-a-class-against-arbitrary-selects" title="Permalink to this headline">¶</a></h2> <p>Similar to mapping against a join, a plain <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.select" title="sqlalchemy.sql.expression.select"><tt class="xref py py-func docutils literal"><span class="pre">select()</span></tt></a> object can be used with a mapper as well. The example fragment below illustrates mapping a class called <tt class="docutils literal"><span class="pre">Customer</span></tt> to a <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.select" title="sqlalchemy.sql.expression.select"><tt class="xref py py-func docutils literal"><span class="pre">select()</span></tt></a> which includes a join to a subquery:</p> <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">select</span><span class="p">,</span> <span class="n">func</span> <span class="n">subq</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span> <span class="n">func</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="n">orders</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="p">)</span><span class="o">.</span><span class="n">label</span><span class="p">(</span><span class="s">'order_count'</span><span class="p">),</span> <span class="n">func</span><span class="o">.</span><span class="n">max</span><span class="p">(</span><span class="n">orders</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">price</span><span class="p">)</span><span class="o">.</span><span class="n">label</span><span class="p">(</span><span class="s">'highest_order'</span><span class="p">),</span> <span class="n">orders</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">customer_id</span> <span class="p">])</span><span class="o">.</span><span class="n">group_by</span><span class="p">(</span><span class="n">orders</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">customer_id</span><span class="p">)</span><span class="o">.</span><span class="n">alias</span><span class="p">()</span> <span class="n">customer_select</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">customers</span><span class="p">,</span> <span class="n">subq</span><span class="p">])</span><span class="o">.</span>\ <span class="n">select_from</span><span class="p">(</span> <span class="n">join</span><span class="p">(</span><span class="n">customers</span><span class="p">,</span> <span class="n">subq</span><span class="p">,</span> <span class="n">customers</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">subq</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">customer_id</span><span class="p">)</span> <span class="p">)</span><span class="o">.</span><span class="n">alias</span><span class="p">()</span> <span class="k">class</span> <span class="nc">Customer</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__table__</span> <span class="o">=</span> <span class="n">customer_select</span></pre></div> </div> <p>Above, the full row represented by <tt class="docutils literal"><span class="pre">customer_select</span></tt> will be all the columns of the <tt class="docutils literal"><span class="pre">customers</span></tt> table, in addition to those columns exposed by the <tt class="docutils literal"><span class="pre">subq</span></tt> subquery, which are <tt class="docutils literal"><span class="pre">order_count</span></tt>, <tt class="docutils literal"><span class="pre">highest_order</span></tt>, and <tt class="docutils literal"><span class="pre">customer_id</span></tt>. Mapping the <tt class="docutils literal"><span class="pre">Customer</span></tt> class to this selectable then creates a class which will contain those attributes.</p> <p>When the ORM persists new instances of <tt class="docutils literal"><span class="pre">Customer</span></tt>, only the <tt class="docutils literal"><span class="pre">customers</span></tt> table will actually receive an INSERT. This is because the primary key of the <tt class="docutils literal"><span class="pre">orders</span></tt> table is not represented in the mapping; the ORM will only emit an INSERT into a table for which it has mapped the primary key.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">The practice of mapping to arbitrary SELECT statements, especially complex ones as above, is almost never needed; it necessarily tends to produce complex queries which are often less efficient than that which would be produced by direct query construction. The practice is to some degree based on the very early history of SQLAlchemy where the <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> construct was meant to represent the primary querying interface; in modern usage, the <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> object can be used to construct virtually any SELECT statement, including complex composites, and should be favored over the “map-to-selectable” approach.</p> </div> </div> <div class="section" id="multiple-mappers-for-one-class"> <h2>Multiple Mappers for One Class<a class="headerlink" href="#multiple-mappers-for-one-class" title="Permalink to this headline">¶</a></h2> <p>In modern SQLAlchemy, a particular class is only mapped by one <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> at a time. The rationale here is that the <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> modifies the class itself, not only persisting it towards a particular <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a>, but also <em>instrumenting</em> attributes upon the class which are structured specifically according to the table metadata.</p> <p>One potential use case for another mapper to exist at the same time is if we wanted to load instances of our class not just from the immediate <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> to which it is mapped, but from another selectable that is a derivation of that <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a>. While there technically is a way to create such a <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a>, using the <tt class="docutils literal"><span class="pre">non_primary=True</span></tt> option, this approach is virtually never needed. Instead, we use the functionality of the <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> object to achieve this, using a method such as <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query.select_from" title="sqlalchemy.orm.query.Query.select_from"><tt class="xref py py-meth docutils literal"><span class="pre">Query.select_from()</span></tt></a> or <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query.from_statement" title="sqlalchemy.orm.query.Query.from_statement"><tt class="xref py py-meth docutils literal"><span class="pre">Query.from_statement()</span></tt></a> to specify a derived selectable.</p> <p>Another potential use is if we genuinely want instances of our class to be persisted into different tables at different times; certain kinds of data sharding configurations may persist a particular class into tables that are identical in structure except for their name. For this kind of pattern, Python offers a better approach than the complexity of mapping the same class multiple times, which is to instead create new mapped classes for each target table. SQLAlchemy refers to this as the “entity name” pattern, which is described as a recipe at <a class="reference external" href="http://www.sqlalchemy.org/trac/wiki/UsageRecipes/EntityName">Entity Name</a>.</p> </div> <div class="section" id="constructors-and-object-initialization"> <span id="mapping-constructors"></span><h2>Constructors and Object Initialization<a class="headerlink" href="#constructors-and-object-initialization" title="Permalink to this headline">¶</a></h2> <p>Mapping imposes no restrictions or requirements on the constructor (<tt class="docutils literal"><span class="pre">__init__</span></tt>) method for the class. You are free to require any arguments for the function that you wish, assign attributes to the instance that are unknown to the ORM, and generally do anything else you would normally do when writing a constructor for a Python class.</p> <p>The SQLAlchemy ORM does not call <tt class="docutils literal"><span class="pre">__init__</span></tt> when recreating objects from database rows. The ORM’s process is somewhat akin to the Python standard library’s <tt class="docutils literal"><span class="pre">pickle</span></tt> module, invoking the low level <tt class="docutils literal"><span class="pre">__new__</span></tt> method and then quietly restoring attributes directly on the instance rather than calling <tt class="docutils literal"><span class="pre">__init__</span></tt>.</p> <p>If you need to do some setup on database-loaded instances before they’re ready to use, you can use the <tt class="docutils literal"><span class="pre">@reconstructor</span></tt> decorator to tag a method as the ORM counterpart to <tt class="docutils literal"><span class="pre">__init__</span></tt>. SQLAlchemy will call this method with no arguments every time it loads or reconstructs one of your instances. This is useful for recreating transient properties that are normally assigned in your <tt class="docutils literal"><span class="pre">__init__</span></tt>:</p> <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">orm</span> <span class="k">class</span> <span class="nc">MyMappedClass</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="n">data</span> <span class="c"># we need stuff on all instances, but not in the database.</span> <span class="bp">self</span><span class="o">.</span><span class="n">stuff</span> <span class="o">=</span> <span class="p">[]</span> <span class="nd">@orm.reconstructor</span> <span class="k">def</span> <span class="nf">init_on_load</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">stuff</span> <span class="o">=</span> <span class="p">[]</span></pre></div> </div> <p>When <tt class="docutils literal"><span class="pre">obj</span> <span class="pre">=</span> <span class="pre">MyMappedClass()</span></tt> is executed, Python calls the <tt class="docutils literal"><span class="pre">__init__</span></tt> method as normal and the <tt class="docutils literal"><span class="pre">data</span></tt> argument is required. When instances are loaded during 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> operation as in <tt class="docutils literal"><span class="pre">query(MyMappedClass).one()</span></tt>, <tt class="docutils literal"><span class="pre">init_on_load</span></tt> is called.</p> <p>Any method may be tagged as the <a class="reference internal" href="#sqlalchemy.orm.reconstructor" title="sqlalchemy.orm.reconstructor"><tt class="xref py py-func docutils literal"><span class="pre">reconstructor()</span></tt></a>, even the <tt class="docutils literal"><span class="pre">__init__</span></tt> method. SQLAlchemy will call the reconstructor method with no arguments. Scalar (non-collection) database-mapped attributes of the instance will be available for use within the function. Eagerly-loaded collections are generally not yet available and will usually only contain the first element. ORM state changes made to objects at this stage will not be recorded for the next flush() operation, so the activity within a reconstructor should be conservative.</p> <p><a class="reference internal" href="#sqlalchemy.orm.reconstructor" title="sqlalchemy.orm.reconstructor"><tt class="xref py py-func docutils literal"><span class="pre">reconstructor()</span></tt></a> is a shortcut into a larger system of “instance level” events, which can be subscribed to using the event API - see <a class="reference internal" href="events.html#sqlalchemy.orm.events.InstanceEvents" title="sqlalchemy.orm.events.InstanceEvents"><tt class="xref py py-class docutils literal"><span class="pre">InstanceEvents</span></tt></a> for the full API description of these events.</p> <dl class="function"> <dt id="sqlalchemy.orm.reconstructor"> <tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">reconstructor</tt><big>(</big><em>fn</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.reconstructor" title="Permalink to this definition">¶</a></dt> <dd><p>Decorate a method as the ‘reconstructor’ hook.</p> <p>Designates a method as the “reconstructor”, an <tt class="docutils literal"><span class="pre">__init__</span></tt>-like method that will be called by the ORM after the instance has been loaded from the database or otherwise reconstituted.</p> <p>The reconstructor will be invoked with no arguments. Scalar (non-collection) database-mapped attributes of the instance will be available for use within the function. Eagerly-loaded collections are generally not yet available and will usually only contain the first element. ORM state changes made to objects at this stage will not be recorded for the next flush() operation, so the activity within a reconstructor should be conservative.</p> </dd></dl> </div> <div class="section" id="configuring-a-version-counter"> <span id="mapper-version-counter"></span><h2>Configuring a Version Counter<a class="headerlink" href="#configuring-a-version-counter" title="Permalink to this headline">¶</a></h2> <p>The <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> supports management of a <em class="xref std std-term">version id column</em>, which is a single table column that increments or otherwise updates its value each time an <tt class="docutils literal"><span class="pre">UPDATE</span></tt> to the mapped table occurs. This value is checked each time the ORM emits an <tt class="docutils literal"><span class="pre">UPDATE</span></tt> or <tt class="docutils literal"><span class="pre">DELETE</span></tt> against the row to ensure that the value held in memory matches the database value.</p> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">Because the versioning feature relies upon comparison of the <strong>in memory</strong> record of an object, the feature only applies to the <a class="reference internal" href="session.html#sqlalchemy.orm.session.Session.flush" title="sqlalchemy.orm.session.Session.flush"><tt class="xref py py-meth docutils literal"><span class="pre">Session.flush()</span></tt></a> process, where the ORM flushes individual in-memory rows to the database. It does <strong>not</strong> take effect when performing a multirow UPDATE or DELETE using <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query.update" title="sqlalchemy.orm.query.Query.update"><tt class="xref py py-meth docutils literal"><span class="pre">Query.update()</span></tt></a> or <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query.delete" title="sqlalchemy.orm.query.Query.delete"><tt class="xref py py-meth docutils literal"><span class="pre">Query.delete()</span></tt></a> methods, as these methods only emit an UPDATE or DELETE statement but otherwise do not have direct access to the contents of those rows being affected.</p> </div> <p>The purpose of this feature is to detect when two concurrent transactions are modifying the same row at roughly the same time, or alternatively to provide a guard against the usage of a “stale” row in a system that might be re-using data from a previous transaction without refreshing (e.g. if one sets <tt class="docutils literal"><span class="pre">expire_on_commit=False</span></tt> with 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>, it is possible to re-use the data from a previous transaction).</p> <div class="topic"> <p class="topic-title first">Concurrent transaction updates</p> <p>When detecting concurrent updates within transactions, it is typically the case that the database’s transaction isolation level is below the level of <em class="xref std std-term">repeatable read</em>; otherwise, the transaction will not be exposed to a new row value created by a concurrent update which conflicts with the locally updated value. In this case, the SQLAlchemy versioning feature will typically not be useful for in-transaction conflict detection, though it still can be used for cross-transaction staleness detection.</p> <p>The database that enforces repeatable reads will typically either have locked the target row against a concurrent update, or is employing some form of multi version concurrency control such that it will emit an error when the transaction is committed. SQLAlchemy’s version_id_col is an alternative which allows version tracking to occur for specific tables within a transaction that otherwise might not have this isolation level set.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference external" href="http://www.postgresql.org/docs/9.1/static/transaction-iso.html#XACT-REPEATABLE-READ">Repeatable Read Isolation Level</a> - Postgresql’s implementation of repeatable read, including a description of the error condition.</p> </div> </div> <div class="section" id="simple-version-counting"> <h3>Simple Version Counting<a class="headerlink" href="#simple-version-counting" title="Permalink to this headline">¶</a></h3> <p>The most straightforward way to track versions is to add an integer column to the mapped table, then establish it as the <tt class="docutils literal"><span class="pre">version_id_col</span></tt> within the mapper options:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'user'</span> <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> <span class="n">version_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">nullable</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span> <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><span class="mi">50</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span> <span class="n">__mapper_args__</span> <span class="o">=</span> <span class="p">{</span> <span class="s">"version_id_col"</span><span class="p">:</span> <span class="n">version_id</span> <span class="p">}</span></pre></div> </div> <p>Above, the <tt class="docutils literal"><span class="pre">User</span></tt> mapping tracks integer versions using the column <tt class="docutils literal"><span class="pre">version_id</span></tt>. When an object of type <tt class="docutils literal"><span class="pre">User</span></tt> is first flushed, the <tt class="docutils literal"><span class="pre">version_id</span></tt> column will be given a value of “1”. Then, an UPDATE of the table later on will always be emitted in a manner similar to the following:</p> <div class="highlight-python"><pre>UPDATE user SET version_id=:version_id, name=:name WHERE user.id = :user_id AND user.version_id = :user_version_id {"name": "new name", "version_id": 2, "user_id": 1, "user_version_id": 1}</pre> </div> <p>The above UPDATE statement is updating the row that not only matches <tt class="docutils literal"><span class="pre">user.id</span> <span class="pre">=</span> <span class="pre">1</span></tt>, it also is requiring that <tt class="docutils literal"><span class="pre">user.version_id</span> <span class="pre">=</span> <span class="pre">1</span></tt>, where “1” is the last version identifier we’ve been known to use on this object. If a transaction elsewhere has modifed the row independently, this version id will no longer match, and the UPDATE statement will report that no rows matched; this is the condition that SQLAlchemy tests, that exactly one row matched our UPDATE (or DELETE) statement. If zero rows match, that indicates our version of the data is stale, and a <tt class="xref py py-class docutils literal"><span class="pre">StaleDataError</span></tt> is raised.</p> </div> <div class="section" id="custom-version-counters-types"> <span id="custom-version-counter"></span><h3>Custom Version Counters / Types<a class="headerlink" href="#custom-version-counters-types" title="Permalink to this headline">¶</a></h3> <p>Other kinds of values or counters can be used for versioning. Common types include dates and GUIDs. When using an alternate type or counter scheme, SQLAlchemy provides a hook for this scheme using the <tt class="docutils literal"><span class="pre">version_id_generator</span></tt> argument, which accepts a version generation callable. This callable is passed the value of the current known version, and is expected to return the subsequent version.</p> <p>For example, if we wanted to track the versioning of our <tt class="docutils literal"><span class="pre">User</span></tt> class using a randomly generated GUID, we could do this (note that some backends support a native GUID type, but we illustrate here using a simple string):</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">uuid</span> <span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'user'</span> <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> <span class="n">version_uuid</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">32</span><span class="p">))</span> <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><span class="mi">50</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span> <span class="n">__mapper_args__</span> <span class="o">=</span> <span class="p">{</span> <span class="s">'version_id_col'</span><span class="p">:</span><span class="n">version_uuid</span><span class="p">,</span> <span class="s">'version_id_generator'</span><span class="p">:</span><span class="k">lambda</span> <span class="n">version</span><span class="p">:</span> <span class="n">uuid</span><span class="o">.</span><span class="n">uuid4</span><span class="p">()</span><span class="o">.</span><span class="n">hex</span> <span class="p">}</span></pre></div> </div> <p>The persistence engine will call upon <tt class="docutils literal"><span class="pre">uuid.uuid4()</span></tt> each time a <tt class="docutils literal"><span class="pre">User</span></tt> object is subject to an INSERT or an UPDATE. In this case, our version generation function can disregard the incoming value of <tt class="docutils literal"><span class="pre">version</span></tt>, as the <tt class="docutils literal"><span class="pre">uuid4()</span></tt> function generates identifiers without any prerequisite value. If we were using a sequential versioning scheme such as numeric or a special character system, we could make use of the given <tt class="docutils literal"><span class="pre">version</span></tt> in order to help determine the subsequent value.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="../core/types.html#custom-guid-type"><em>Backend-agnostic GUID Type</em></a></p> </div> </div> </div> <div class="section" id="class-mapping-api"> <h2>Class Mapping API<a class="headerlink" href="#class-mapping-api" title="Permalink to this headline">¶</a></h2> <dl class="function"> <dt id="sqlalchemy.orm.mapper"> <tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">mapper</tt><big>(</big><em>class_</em>, <em>local_table=None</em>, <em>*args</em>, <em>**params</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper" title="Permalink to this definition">¶</a></dt> <dd><p>Return a new <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> object.</p> <p>This function is typically used behind the scenes via the Declarative extension. When using Declarative, many of the usual <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> arguments are handled by the Declarative extension itself, including <tt class="docutils literal"><span class="pre">class_</span></tt>, <tt class="docutils literal"><span class="pre">local_table</span></tt>, <tt class="docutils literal"><span class="pre">properties</span></tt>, and <tt class="docutils literal"><span class="pre">inherits</span></tt>. Other options are passed to <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> using the <tt class="docutils literal"><span class="pre">__mapper_args__</span></tt> class variable:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">MyClass</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'my_table'</span> <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> <span class="nb">type</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> <span class="n">alt</span> <span class="o">=</span> <span class="n">Column</span><span class="p">(</span><span class="s">"some_alt"</span><span class="p">,</span> <span class="n">Integer</span><span class="p">)</span> <span class="n">__mapper_args__</span> <span class="o">=</span> <span class="p">{</span> <span class="s">'polymorphic_on'</span> <span class="p">:</span> <span class="nb">type</span> <span class="p">}</span></pre></div> </div> <p>Explicit use of <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> is often referred to as <em>classical mapping</em>. The above declarative example is equivalent in classical form to:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">my_table</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s">"my_table"</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="n">Column</span><span class="p">(</span><span class="s">'id'</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> <span class="n">Column</span><span class="p">(</span><span class="s">'type'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">50</span><span class="p">)),</span> <span class="n">Column</span><span class="p">(</span><span class="s">"some_alt"</span><span class="p">,</span> <span class="n">Integer</span><span class="p">)</span> <span class="p">)</span> <span class="k">class</span> <span class="nc">MyClass</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">pass</span> <span class="n">mapper</span><span class="p">(</span><span class="n">MyClass</span><span class="p">,</span> <span class="n">my_table</span><span class="p">,</span> <span class="n">polymorphic_on</span><span class="o">=</span><span class="n">my_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">type</span><span class="p">,</span> <span class="n">properties</span><span class="o">=</span><span class="p">{</span> <span class="s">'alt'</span><span class="p">:</span><span class="n">my_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">some_alt</span> <span class="p">})</span></pre></div> </div> <p>See also:</p> <p><a class="reference internal" href="#classical-mapping"><em>Classical Mappings</em></a> - discussion of direct usage of <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a></p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><span class="target" id="sqlalchemy.orm.mapper.params.class_"></span><strong>class_</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.class_">¶</a> – The class to be mapped. When using Declarative, this argument is automatically passed as the declared class itself.</li> <li><span class="target" id="sqlalchemy.orm.mapper.params.local_table"></span><strong>local_table</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.local_table">¶</a> – The <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> or other selectable to which the class is mapped. May be <tt class="docutils literal"><span class="pre">None</span></tt> if this mapper inherits from another mapper using single-table inheritance. When using Declarative, this argument is automatically passed by the extension, based on what is configured via the <tt class="docutils literal"><span class="pre">__table__</span></tt> argument or via the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> produced as a result of the <tt class="docutils literal"><span class="pre">__tablename__</span></tt> and <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> arguments present.</li> <li><span class="target" id="sqlalchemy.orm.mapper.params.always_refresh"></span><strong>always_refresh</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.always_refresh">¶</a> – If True, all query operations for this mapped class will overwrite all data within object instances that already exist within the session, erasing any in-memory changes with whatever information was loaded from the database. Usage of this flag is highly discouraged; as an alternative, see the method <a class="reference internal" href="query.html#sqlalchemy.orm.query.Query.populate_existing" title="sqlalchemy.orm.query.Query.populate_existing"><tt class="xref py py-meth docutils literal"><span class="pre">Query.populate_existing()</span></tt></a>.</li> <li><span class="target" id="sqlalchemy.orm.mapper.params.allow_partial_pks"></span><strong>allow_partial_pks</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.allow_partial_pks">¶</a> – Defaults to True. Indicates that a composite primary key with some NULL values should be considered as possibly existing within the database. This affects whether a mapper will assign an incoming row to an existing identity, as well as if <a class="reference internal" href="session.html#sqlalchemy.orm.session.Session.merge" title="sqlalchemy.orm.session.Session.merge"><tt class="xref py py-meth docutils literal"><span class="pre">Session.merge()</span></tt></a> will check the database first for a particular primary key value. A “partial primary key” can occur if one has mapped to an OUTER JOIN, for example.</li> <li><span class="target" id="sqlalchemy.orm.mapper.params.batch"></span><strong>batch</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.batch">¶</a> – Defaults to <tt class="docutils literal"><span class="pre">True</span></tt>, indicating that save operations of multiple entities can be batched together for efficiency. Setting to False indicates that an instance will be fully saved before saving the next instance. This is used in the extremely rare case that a <a class="reference internal" href="events.html#sqlalchemy.orm.events.MapperEvents" title="sqlalchemy.orm.events.MapperEvents"><tt class="xref py py-class docutils literal"><span class="pre">MapperEvents</span></tt></a> listener requires being called in between individual row persistence operations.</li> <li><span class="target" id="sqlalchemy.orm.mapper.params.column_prefix"></span><strong>column_prefix</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.column_prefix">¶</a> – <p>A string which will be prepended to the mapped attribute name when <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> objects are automatically assigned as attributes to the mapped class. Does not affect explicitly specified column-based properties.</p> <p>See the section <a class="reference internal" href="#column-prefix"><em>Naming All Columns with a Prefix</em></a> for an example.</p> </li> <li><span class="target" id="sqlalchemy.orm.mapper.params.concrete"></span><strong>concrete</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.concrete">¶</a> – <p>If True, indicates this mapper should use concrete table inheritance with its parent mapper.</p> <p>See the section <a class="reference internal" href="inheritance.html#concrete-inheritance"><em>Concrete Table Inheritance</em></a> for an example.</p> </li> <li><span class="target" id="sqlalchemy.orm.mapper.params.eager_defaults"></span><strong>eager_defaults</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.eager_defaults">¶</a> – if True, the ORM will immediately fetch the value of server-generated default values after an INSERT or UPDATE, rather than leaving them as expired to be fetched on next access. This can be used for event schemes where the server-generated values are needed immediately before the flush completes. This scheme will emit an individual <tt class="docutils literal"><span class="pre">SELECT</span></tt> statement per row inserted or updated, which note can add significant performance overhead.</li> <li><span class="target" id="sqlalchemy.orm.mapper.params.exclude_properties"></span><strong>exclude_properties</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.exclude_properties">¶</a> – <p>A list or set of string column names to be excluded from mapping.</p> <p>See <a class="reference internal" href="#include-exclude-cols"><em>Mapping a Subset of Table Columns</em></a> for an example.</p> </li> <li><span class="target" id="sqlalchemy.orm.mapper.params.extension"></span><strong>extension</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.extension">¶</a> – A <a class="reference internal" href="deprecated.html#sqlalchemy.orm.interfaces.MapperExtension" title="sqlalchemy.orm.interfaces.MapperExtension"><tt class="xref py py-class docutils literal"><span class="pre">MapperExtension</span></tt></a> instance or list of <a class="reference internal" href="deprecated.html#sqlalchemy.orm.interfaces.MapperExtension" title="sqlalchemy.orm.interfaces.MapperExtension"><tt class="xref py py-class docutils literal"><span class="pre">MapperExtension</span></tt></a> instances which will be applied to all operations by this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a>. <strong>Deprecated.</strong> Please see <a class="reference internal" href="events.html#sqlalchemy.orm.events.MapperEvents" title="sqlalchemy.orm.events.MapperEvents"><tt class="xref py py-class docutils literal"><span class="pre">MapperEvents</span></tt></a>.</li> <li><span class="target" id="sqlalchemy.orm.mapper.params.include_properties"></span><strong>include_properties</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.include_properties">¶</a> – <p>An inclusive list or set of string column names to map.</p> <p>See <a class="reference internal" href="#include-exclude-cols"><em>Mapping a Subset of Table Columns</em></a> for an example.</p> </li> <li><span class="target" id="sqlalchemy.orm.mapper.params.inherits"></span><strong>inherits</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.inherits">¶</a> – <p>A mapped class or the corresponding <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> of one indicating a superclass to which this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> should <em>inherit</em> from. The mapped class here must be a subclass of the other mapper’s class. When using Declarative, this argument is passed automatically as a result of the natural class hierarchy of the declared classes.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="inheritance.html"><em>Mapping Class Inheritance Hierarchies</em></a></p> </div> </li> <li><span class="target" id="sqlalchemy.orm.mapper.params.inherit_condition"></span><strong>inherit_condition</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.inherit_condition">¶</a> – For joined table inheritance, a SQL expression which will define how the two tables are joined; defaults to a natural join between the two tables.</li> <li><span class="target" id="sqlalchemy.orm.mapper.params.inherit_foreign_keys"></span><strong>inherit_foreign_keys</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.inherit_foreign_keys">¶</a> – When <tt class="docutils literal"><span class="pre">inherit_condition</span></tt> is used and the columns present are missing a <a class="reference internal" href="../core/constraints.html#sqlalchemy.schema.ForeignKey" title="sqlalchemy.schema.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a> configuration, this parameter can be used to specify which columns are “foreign”. In most cases can be left as <tt class="docutils literal"><span class="pre">None</span></tt>.</li> <li><span class="target" id="sqlalchemy.orm.mapper.params.legacy_is_orphan"></span><strong>legacy_is_orphan</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.legacy_is_orphan">¶</a> – <p>Boolean, defaults to <tt class="docutils literal"><span class="pre">False</span></tt>. When <tt class="docutils literal"><span class="pre">True</span></tt>, specifies that “legacy” orphan consideration is to be applied to objects mapped by this mapper, which means that a pending (that is, not persistent) object is auto-expunged from an owning <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> only when it is de-associated from <em>all</em> parents that specify a <tt class="docutils literal"><span class="pre">delete-orphan</span></tt> cascade towards this mapper. The new default behavior is that the object is auto-expunged when it is de-associated with <em>any</em> of its parents that specify <tt class="docutils literal"><span class="pre">delete-orphan</span></tt> cascade. This behavior is more consistent with that of a persistent object, and allows behavior to be consistent in more scenarios independently of whether or not an orphanable object has been flushed yet or not.</p> <p>See the change note and example at <a class="reference internal" href="../changelog/migration_08.html#legacy-is-orphan-addition"><em>The consideration of a “pending” object as an “orphan” has been made more aggressive</em></a> for more detail on this change.</p> <div class="versionadded"> <p><span>New in version 0.8: </span>- the consideration of a pending object as an “orphan” has been modified to more closely match the behavior as that of persistent objects, which is that the object is expunged from the <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> as soon as it is de-associated from any of its orphan-enabled parents. Previously, the pending object would be expunged only if de-associated from all of its orphan-enabled parents. The new flag <tt class="docutils literal"><span class="pre">legacy_is_orphan</span></tt> is added to <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">orm.mapper()</span></tt></a> which re-establishes the legacy behavior.</p> </div> </li> <li><span class="target" id="sqlalchemy.orm.mapper.params.non_primary"></span><strong>non_primary</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.non_primary">¶</a> – <p>Specify that this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> is in addition to the “primary” mapper, that is, the one used for persistence. The <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> created here may be used for ad-hoc mapping of the class to an alternate selectable, for loading only.</p> <p>The <tt class="docutils literal"><span class="pre">non_primary</span></tt> feature is rarely needed with modern usage.</p> </li> <li><span class="target" id="sqlalchemy.orm.mapper.params.order_by"></span><strong>order_by</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.order_by">¶</a> – A single <a class="reference internal" href="../core/metadata.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 of <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> objects for which selection operations should use as the default ordering for entities. By default mappers have no pre-defined ordering.</li> <li><span class="target" id="sqlalchemy.orm.mapper.params.passive_updates"></span><strong>passive_updates</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.passive_updates">¶</a> – <p>Indicates UPDATE behavior of foreign key columns when a primary key column changes on a joined-table inheritance mapping. Defaults to <tt class="docutils literal"><span class="pre">True</span></tt>.</p> <p>When True, it is assumed that ON UPDATE CASCADE is configured on the foreign key in the database, and that the database will handle propagation of an UPDATE from a source column to dependent columns on joined-table rows.</p> <p>When False, it is assumed that the database does not enforce referential integrity and will not be issuing its own CASCADE operation for an update. The unit of work process will emit an UPDATE statement for the dependent columns during a primary key change.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="relationships.html#passive-updates"><em>Mutable Primary Keys / Update Cascades</em></a> - description of a similar feature as used with <a class="reference internal" href="relationships.html#sqlalchemy.orm.relationship" title="sqlalchemy.orm.relationship"><tt class="xref py py-func docutils literal"><span class="pre">relationship()</span></tt></a></p> </div> </li> <li><span class="target" id="sqlalchemy.orm.mapper.params.polymorphic_on"></span><strong>polymorphic_on</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.polymorphic_on">¶</a> – <p>Specifies the column, attribute, or SQL expression used to determine the target class for an incoming row, when inheriting classes are present.</p> <p>This value is commonly a <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> object that’s present in the mapped <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Employee</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'employee'</span> <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> <span class="n">discriminator</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> <span class="n">__mapper_args__</span> <span class="o">=</span> <span class="p">{</span> <span class="s">"polymorphic_on"</span><span class="p">:</span><span class="n">discriminator</span><span class="p">,</span> <span class="s">"polymorphic_identity"</span><span class="p">:</span><span class="s">"employee"</span> <span class="p">}</span></pre></div> </div> <p>It may also be specified as a SQL expression, as in this example where we use the <a class="reference internal" href="../core/sqlelement.html#sqlalchemy.sql.expression.case" title="sqlalchemy.sql.expression.case"><tt class="xref py py-func docutils literal"><span class="pre">case()</span></tt></a> construct to provide a conditional approach:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Employee</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'employee'</span> <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> <span class="n">discriminator</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> <span class="n">__mapper_args__</span> <span class="o">=</span> <span class="p">{</span> <span class="s">"polymorphic_on"</span><span class="p">:</span><span class="n">case</span><span class="p">([</span> <span class="p">(</span><span class="n">discriminator</span> <span class="o">==</span> <span class="s">"EN"</span><span class="p">,</span> <span class="s">"engineer"</span><span class="p">),</span> <span class="p">(</span><span class="n">discriminator</span> <span class="o">==</span> <span class="s">"MA"</span><span class="p">,</span> <span class="s">"manager"</span><span class="p">),</span> <span class="p">],</span> <span class="n">else_</span><span class="o">=</span><span class="s">"employee"</span><span class="p">),</span> <span class="s">"polymorphic_identity"</span><span class="p">:</span><span class="s">"employee"</span> <span class="p">}</span></pre></div> </div> <p>It may also refer to any attribute configured with <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">column_property()</span></tt></a>, or to the string name of one:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Employee</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">'employee'</span> <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> <span class="n">discriminator</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> <span class="n">employee_type</span> <span class="o">=</span> <span class="n">column_property</span><span class="p">(</span> <span class="n">case</span><span class="p">([</span> <span class="p">(</span><span class="n">discriminator</span> <span class="o">==</span> <span class="s">"EN"</span><span class="p">,</span> <span class="s">"engineer"</span><span class="p">),</span> <span class="p">(</span><span class="n">discriminator</span> <span class="o">==</span> <span class="s">"MA"</span><span class="p">,</span> <span class="s">"manager"</span><span class="p">),</span> <span class="p">],</span> <span class="n">else_</span><span class="o">=</span><span class="s">"employee"</span><span class="p">)</span> <span class="p">)</span> <span class="n">__mapper_args__</span> <span class="o">=</span> <span class="p">{</span> <span class="s">"polymorphic_on"</span><span class="p">:</span><span class="n">employee_type</span><span class="p">,</span> <span class="s">"polymorphic_identity"</span><span class="p">:</span><span class="s">"employee"</span> <span class="p">}</span></pre></div> </div> <div class="versionchanged"> <p><span>Changed in version 0.7.4: </span><tt class="docutils literal"><span class="pre">polymorphic_on</span></tt> may be specified as a SQL expression, or refer to any attribute configured with <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">column_property()</span></tt></a>, or to the string name of one.</p> </div> <p>When setting <tt class="docutils literal"><span class="pre">polymorphic_on</span></tt> to reference an attribute or expression that’s not present in the locally mapped <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a>, yet the value of the discriminator should be persisted to the database, the value of the discriminator is not automatically set on new instances; this must be handled by the user, either through manual means or via event listeners. A typical approach to establishing such a listener looks like:</p> <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">event</span> <span class="kn">from</span> <span class="nn">sqlalchemy.orm</span> <span class="kn">import</span> <span class="n">object_mapper</span> <span class="nd">@event.listens_for</span><span class="p">(</span><span class="n">Employee</span><span class="p">,</span> <span class="s">"init"</span><span class="p">,</span> <span class="n">propagate</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="k">def</span> <span class="nf">set_identity</span><span class="p">(</span><span class="n">instance</span><span class="p">,</span> <span class="o">*</span><span class="n">arg</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span> <span class="n">mapper</span> <span class="o">=</span> <span class="n">object_mapper</span><span class="p">(</span><span class="n">instance</span><span class="p">)</span> <span class="n">instance</span><span class="o">.</span><span class="n">discriminator</span> <span class="o">=</span> <span class="n">mapper</span><span class="o">.</span><span class="n">polymorphic_identity</span></pre></div> </div> <p>Where above, we assign the value of <tt class="docutils literal"><span class="pre">polymorphic_identity</span></tt> for the mapped class to the <tt class="docutils literal"><span class="pre">discriminator</span></tt> attribute, thus persisting the value to the <tt class="docutils literal"><span class="pre">discriminator</span></tt> column in the database.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="inheritance.html"><em>Mapping Class Inheritance Hierarchies</em></a></p> </div> </li> <li><span class="target" id="sqlalchemy.orm.mapper.params.polymorphic_identity"></span><strong>polymorphic_identity</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.polymorphic_identity">¶</a> – Specifies the value which identifies this particular class as returned by the column expression referred to by the <tt class="docutils literal"><span class="pre">polymorphic_on</span></tt> setting. As rows are received, the value corresponding to the <tt class="docutils literal"><span class="pre">polymorphic_on</span></tt> column expression is compared to this value, indicating which subclass should be used for the newly reconstructed object.</li> <li><span class="target" id="sqlalchemy.orm.mapper.params.properties"></span><strong>properties</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.properties">¶</a> – A dictionary mapping the string names of object attributes to <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces.MapperProperty" title="sqlalchemy.orm.interfaces.MapperProperty"><tt class="xref py py-class docutils literal"><span class="pre">MapperProperty</span></tt></a> instances, which define the persistence behavior of that attribute. Note that <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> objects present in the mapped <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> are automatically placed into <tt class="docutils literal"><span class="pre">ColumnProperty</span></tt> instances upon mapping, unless overridden. When using Declarative, this argument is passed automatically, based on all those <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces.MapperProperty" title="sqlalchemy.orm.interfaces.MapperProperty"><tt class="xref py py-class docutils literal"><span class="pre">MapperProperty</span></tt></a> instances declared in the declared class body.</li> <li><span class="target" id="sqlalchemy.orm.mapper.params.primary_key"></span><strong>primary_key</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.primary_key">¶</a> – A list of <a class="reference internal" href="../core/metadata.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 define the primary key to be used against this mapper’s selectable unit. This is normally simply the primary key of the <tt class="docutils literal"><span class="pre">local_table</span></tt>, but can be overridden here.</li> <li><span class="target" id="sqlalchemy.orm.mapper.params.version_id_col"></span><strong>version_id_col</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.version_id_col">¶</a> – <p>A <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> that will be used to keep a running version id of rows in the table. This is used to detect concurrent updates or the presence of stale data in a flush. The methodology is to detect if an UPDATE statement does not match the last known version id, a <a class="reference internal" href="exceptions.html#sqlalchemy.orm.exc.StaleDataError" title="sqlalchemy.orm.exc.StaleDataError"><tt class="xref py py-class docutils literal"><span class="pre">StaleDataError</span></tt></a> exception is thrown. By default, the column must be of <a class="reference internal" href="../core/types.html#sqlalchemy.types.Integer" title="sqlalchemy.types.Integer"><tt class="xref py py-class docutils literal"><span class="pre">Integer</span></tt></a> type, unless <tt class="docutils literal"><span class="pre">version_id_generator</span></tt> specifies an alternative version generator.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="#mapper-version-counter"><em>Configuring a Version Counter</em></a> - discussion of version counting and rationale.</p> </div> </li> <li><span class="target" id="sqlalchemy.orm.mapper.params.version_id_generator"></span><strong>version_id_generator</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.version_id_generator">¶</a> – <p>Define how new version ids should be generated. Defaults to <tt class="docutils literal"><span class="pre">None</span></tt>, which indicates that a simple integer counting scheme be employed. To provide a custom versioning scheme, provide a callable function of the form:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">generate_version</span><span class="p">(</span><span class="n">version</span><span class="p">):</span> <span class="k">return</span> <span class="n">next_version</span></pre></div> </div> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="#custom-version-counter"><em>Custom Version Counters / Types</em></a></p> </div> </li> <li><span class="target" id="sqlalchemy.orm.mapper.params.with_polymorphic"></span><strong>with_polymorphic</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.params.with_polymorphic">¶</a> – <p>A tuple in the form <tt class="docutils literal"><span class="pre">(<classes>,</span> <span class="pre"><selectable>)</span></tt> indicating the default style of “polymorphic” loading, that is, which tables are queried at once. <classes> is any single or list of mappers and/or classes indicating the inherited classes that should be loaded at once. The special value <tt class="docutils literal"><span class="pre">'*'</span></tt> may be used to indicate all descending classes should be loaded immediately. The second tuple argument <selectable> indicates a selectable that will be used to query for multiple classes.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="inheritance.html#with-polymorphic"><em>Basic Control of Which Tables are Queried</em></a></p> </div> </li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="function"> <dt id="sqlalchemy.orm.object_mapper"> <tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">object_mapper</tt><big>(</big><em>instance</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.object_mapper" title="Permalink to this definition">¶</a></dt> <dd><p>Given an object, return the primary Mapper associated with the object instance.</p> <p>Raises <a class="reference internal" href="exceptions.html#sqlalchemy.orm.exc.UnmappedInstanceError" title="sqlalchemy.orm.exc.UnmappedInstanceError"><tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.orm.exc.UnmappedInstanceError</span></tt></a> if no mapping is configured.</p> <p>This function is available via the inspection system as:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">inspect</span><span class="p">(</span><span class="n">instance</span><span class="p">)</span><span class="o">.</span><span class="n">mapper</span></pre></div> </div> <p>Using the inspection system will raise <a class="reference internal" href="../core/exceptions.html#sqlalchemy.exc.NoInspectionAvailable" title="sqlalchemy.exc.NoInspectionAvailable"><tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.exc.NoInspectionAvailable</span></tt></a> if the instance is not part of a mapping.</p> </dd></dl> <dl class="function"> <dt id="sqlalchemy.orm.class_mapper"> <tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">class_mapper</tt><big>(</big><em>class_</em>, <em>configure=True</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.class_mapper" title="Permalink to this definition">¶</a></dt> <dd><p>Given a class, return the primary <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> associated with the key.</p> <p>Raises <tt class="xref py py-class docutils literal"><span class="pre">UnmappedClassError</span></tt> if no mapping is configured on the given class, or <tt class="xref py py-class docutils literal"><span class="pre">ArgumentError</span></tt> if a non-class object is passed.</p> <p>Equivalent functionality is available via the <a class="reference internal" href="../core/inspection.html#sqlalchemy.inspection.inspect" title="sqlalchemy.inspection.inspect"><tt class="xref py py-func docutils literal"><span class="pre">inspect()</span></tt></a> function as:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">inspect</span><span class="p">(</span><span class="n">some_mapped_class</span><span class="p">)</span></pre></div> </div> <p>Using the inspection system will raise <a class="reference internal" href="../core/exceptions.html#sqlalchemy.exc.NoInspectionAvailable" title="sqlalchemy.exc.NoInspectionAvailable"><tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.exc.NoInspectionAvailable</span></tt></a> if the class is not mapped.</p> </dd></dl> <dl class="function"> <dt id="sqlalchemy.orm.configure_mappers"> <tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">configure_mappers</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.configure_mappers" title="Permalink to this definition">¶</a></dt> <dd><p>Initialize the inter-mapper relationships of all mappers that have been constructed thus far.</p> <p>This function can be called any number of times, but in most cases is handled internally.</p> </dd></dl> <dl class="function"> <dt id="sqlalchemy.orm.clear_mappers"> <tt class="descclassname">sqlalchemy.orm.</tt><tt class="descname">clear_mappers</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.clear_mappers" title="Permalink to this definition">¶</a></dt> <dd><p>Remove all mappers from all classes.</p> <p>This function removes all instrumentation from classes and disposes of their associated mappers. Once called, the classes are unmapped and can be later re-mapped with new mappers.</p> <p><a class="reference internal" href="#sqlalchemy.orm.clear_mappers" title="sqlalchemy.orm.clear_mappers"><tt class="xref py py-func docutils literal"><span class="pre">clear_mappers()</span></tt></a> is <em>not</em> for normal use, as there is literally no valid usage for it outside of very specific testing scenarios. Normally, mappers are permanent structural components of user-defined classes, and are never discarded independently of their class. If a mapped class itself is garbage collected, its mapper is automatically disposed of as well. As such, <a class="reference internal" href="#sqlalchemy.orm.clear_mappers" title="sqlalchemy.orm.clear_mappers"><tt class="xref py py-func docutils literal"><span class="pre">clear_mappers()</span></tt></a> is only for usage in test suites that re-use the same classes with different mappings, which is itself an extremely rare use case - the only such use case is in fact SQLAlchemy’s own test suite, and possibly the test suites of other ORM extension libraries which intend to test various combinations of mapper construction upon a fixed set of classes.</p> </dd></dl> <dl class="function"> <dt id="sqlalchemy.orm.util.identity_key"> <tt class="descclassname">sqlalchemy.orm.util.</tt><tt class="descname">identity_key</tt><big>(</big><em>*args</em>, <em>**kwargs</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.util.identity_key" title="Permalink to this definition">¶</a></dt> <dd><p>Generate “identity key” tuples, as are used as keys in the <a class="reference internal" href="session.html#sqlalchemy.orm.session.Session.identity_map" title="sqlalchemy.orm.session.Session.identity_map"><tt class="xref py py-attr docutils literal"><span class="pre">Session.identity_map</span></tt></a> dictionary.</p> <p>This function has several call styles:</p> <ul> <li><p class="first"><tt class="docutils literal"><span class="pre">identity_key(class,</span> <span class="pre">ident)</span></tt></p> <p>This form receives a mapped class and a primary key scalar or tuple as an argument.</p> <p>E.g.:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">identity_key</span><span class="p">(</span><span class="n">MyClass</span><span class="p">,</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span> <span class="go">(<class '__main__.MyClass'>, (1, 2))</span></pre></div> </div> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">param class:</th><td class="field-body">mapped class (must be a positional argument)</td> </tr> <tr class="field-even field"><th class="field-name">param ident:</th><td class="field-body">primary key, may be a scalar or tuple argument.</td> </tr> </tbody> </table> </li> <li><p class="first"><tt class="docutils literal"><span class="pre">identity_key(instance=instance)</span></tt></p> <p>This form will produce the identity key for a given instance. The instance need not be persistent, only that its primary key attributes are populated (else the key will contain <tt class="docutils literal"><span class="pre">None</span></tt> for those missing values).</p> <p>E.g.:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">instance</span> <span class="o">=</span> <span class="n">MyClass</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">identity_key</span><span class="p">(</span><span class="n">instance</span><span class="o">=</span><span class="n">instance</span><span class="p">)</span> <span class="go">(<class '__main__.MyClass'>, (1, 2))</span></pre></div> </div> <p>In this form, the given instance is ultimately run though <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.identity_key_from_instance" title="sqlalchemy.orm.mapper.Mapper.identity_key_from_instance"><tt class="xref py py-meth docutils literal"><span class="pre">Mapper.identity_key_from_instance()</span></tt></a>, which will have the effect of performing a database check for the corresponding row if the object is expired.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">param instance:</th><td class="field-body">object instance (must be given as a keyword arg)</td> </tr> </tbody> </table> </li> <li><p class="first"><tt class="docutils literal"><span class="pre">identity_key(class,</span> <span class="pre">row=row)</span></tt></p> <p>This form is similar to the class/tuple form, except is passed a database result row as a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.RowProxy" title="sqlalchemy.engine.RowProxy"><tt class="xref py py-class docutils literal"><span class="pre">RowProxy</span></tt></a> object.</p> <p>E.g.:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">row</span> <span class="o">=</span> <span class="n">engine</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">"select * from table where a=1 and b=2"</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">identity_key</span><span class="p">(</span><span class="n">MyClass</span><span class="p">,</span> <span class="n">row</span><span class="o">=</span><span class="n">row</span><span class="p">)</span> <span class="go">(<class '__main__.MyClass'>, (1, 2))</span></pre></div> </div> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">param class:</th><td class="field-body">mapped class (must be a positional argument)</td> </tr> <tr class="field-even field"><th class="field-name">param row:</th><td class="field-body"><a class="reference internal" href="../core/connections.html#sqlalchemy.engine.RowProxy" title="sqlalchemy.engine.RowProxy"><tt class="xref py py-class docutils literal"><span class="pre">RowProxy</span></tt></a> row returned by a <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.ResultProxy" title="sqlalchemy.engine.ResultProxy"><tt class="xref py py-class docutils literal"><span class="pre">ResultProxy</span></tt></a> (must be given as a keyword arg)</td> </tr> </tbody> </table> </li> </ul> </dd></dl> <dl class="function"> <dt id="sqlalchemy.orm.util.polymorphic_union"> <tt class="descclassname">sqlalchemy.orm.util.</tt><tt class="descname">polymorphic_union</tt><big>(</big><em>table_map</em>, <em>typecolname</em>, <em>aliasname='p_union'</em>, <em>cast_nulls=True</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.util.polymorphic_union" title="Permalink to this definition">¶</a></dt> <dd><p>Create a <tt class="docutils literal"><span class="pre">UNION</span></tt> statement used by a polymorphic mapper.</p> <p>See <a class="reference internal" href="inheritance.html#concrete-inheritance"><em>Concrete Table Inheritance</em></a> for an example of how this is used.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><span class="target" id="sqlalchemy.orm.util.polymorphic_union.params.table_map"></span><strong>table_map</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.util.polymorphic_union.params.table_map">¶</a> – mapping of polymorphic identities to <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> objects.</li> <li><span class="target" id="sqlalchemy.orm.util.polymorphic_union.params.typecolname"></span><strong>typecolname</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.util.polymorphic_union.params.typecolname">¶</a> – string name of a “discriminator” column, which will be derived from the query, producing the polymorphic identity for each row. If <tt class="docutils literal"><span class="pre">None</span></tt>, no polymorphic discriminator is generated.</li> <li><span class="target" id="sqlalchemy.orm.util.polymorphic_union.params.aliasname"></span><strong>aliasname</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.util.polymorphic_union.params.aliasname">¶</a> – name of the <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.alias" title="sqlalchemy.sql.expression.alias"><tt class="xref py py-func docutils literal"><span class="pre">alias()</span></tt></a> construct generated.</li> <li><span class="target" id="sqlalchemy.orm.util.polymorphic_union.params.cast_nulls"></span><strong>cast_nulls</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.util.polymorphic_union.params.cast_nulls">¶</a> – if True, non-existent columns, which are represented as labeled NULLs, will be passed into CAST. This is a legacy behavior that is problematic on some backends such as Oracle - in which case it can be set to False.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="class"> <dt id="sqlalchemy.orm.mapper.Mapper"> <em class="property">class </em><tt class="descclassname">sqlalchemy.orm.mapper.</tt><tt class="descname">Mapper</tt><big>(</big><em>class_</em>, <em>local_table</em>, <em>properties=None</em>, <em>primary_key=None</em>, <em>non_primary=False</em>, <em>inherits=None</em>, <em>inherit_condition=None</em>, <em>inherit_foreign_keys=None</em>, <em>extension=None</em>, <em>order_by=False</em>, <em>always_refresh=False</em>, <em>version_id_col=None</em>, <em>version_id_generator=None</em>, <em>polymorphic_on=None</em>, <em>_polymorphic_map=None</em>, <em>polymorphic_identity=None</em>, <em>concrete=False</em>, <em>with_polymorphic=None</em>, <em>allow_partial_pks=True</em>, <em>batch=True</em>, <em>column_prefix=None</em>, <em>include_properties=None</em>, <em>exclude_properties=None</em>, <em>passive_updates=True</em>, <em>eager_defaults=False</em>, <em>legacy_is_orphan=False</em>, <em>_compiled_cache_size=100</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces._InspectionAttr" title="sqlalchemy.orm.interfaces._InspectionAttr"><tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.orm.interfaces._InspectionAttr</span></tt></a></p> <p>Define the correlation of class attributes to database table columns.</p> <p>The <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> object is instantiated using the <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> function. For information about instantiating new <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> objects, see that function’s documentation.</p> <p>When <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> is used explicitly to link a user defined class with table metadata, this is referred to as <em>classical mapping</em>. Modern SQLAlchemy usage tends to favor the <a class="reference internal" href="extensions/declarative.html#module-sqlalchemy.ext.declarative" title="sqlalchemy.ext.declarative"><tt class="xref py py-mod docutils literal"><span class="pre">sqlalchemy.ext.declarative</span></tt></a> extension for class configuration, which makes usage of <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> behind the scenes.</p> <p>Given a particular class known to be mapped by the ORM, the <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> which maintains it can be acquired using the <a class="reference internal" href="../core/inspection.html#sqlalchemy.inspection.inspect" title="sqlalchemy.inspection.inspect"><tt class="xref py py-func docutils literal"><span class="pre">inspect()</span></tt></a> function:</p> <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">inspect</span> <span class="n">mapper</span> <span class="o">=</span> <span class="n">inspect</span><span class="p">(</span><span class="n">MyClass</span><span class="p">)</span></pre></div> </div> <p>A class which was mapped by the <a class="reference internal" href="extensions/declarative.html#module-sqlalchemy.ext.declarative" title="sqlalchemy.ext.declarative"><tt class="xref py py-mod docutils literal"><span class="pre">sqlalchemy.ext.declarative</span></tt></a> extension will also have its mapper available via the <tt class="docutils literal"><span class="pre">__mapper__</span></tt> attribute.</p> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.__init__"> <tt class="descname">__init__</tt><big>(</big><em>class_</em>, <em>local_table</em>, <em>properties=None</em>, <em>primary_key=None</em>, <em>non_primary=False</em>, <em>inherits=None</em>, <em>inherit_condition=None</em>, <em>inherit_foreign_keys=None</em>, <em>extension=None</em>, <em>order_by=False</em>, <em>always_refresh=False</em>, <em>version_id_col=None</em>, <em>version_id_generator=None</em>, <em>polymorphic_on=None</em>, <em>_polymorphic_map=None</em>, <em>polymorphic_identity=None</em>, <em>concrete=False</em>, <em>with_polymorphic=None</em>, <em>allow_partial_pks=True</em>, <em>batch=True</em>, <em>column_prefix=None</em>, <em>include_properties=None</em>, <em>exclude_properties=None</em>, <em>passive_updates=True</em>, <em>eager_defaults=False</em>, <em>legacy_is_orphan=False</em>, <em>_compiled_cache_size=100</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.__init__" title="Permalink to this definition">¶</a></dt> <dd><p>Construct a new mapper.</p> <p>Mappers are normally constructed via the <a class="reference internal" href="#sqlalchemy.orm.mapper" title="sqlalchemy.orm.mapper"><tt class="xref py py-func docutils literal"><span class="pre">mapper()</span></tt></a> function. See for details.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.add_properties"> <tt class="descname">add_properties</tt><big>(</big><em>dict_of_properties</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.add_properties" title="Permalink to this definition">¶</a></dt> <dd><p>Add the given dictionary of properties to this mapper, using <cite>add_property</cite>.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.add_property"> <tt class="descname">add_property</tt><big>(</big><em>key</em>, <em>prop</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.add_property" title="Permalink to this definition">¶</a></dt> <dd><p>Add an individual MapperProperty to this mapper.</p> <p>If the mapper has not been configured yet, just adds the property to the initial properties dictionary sent to the constructor. If this Mapper has already been configured, then the given MapperProperty is configured immediately.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.all_orm_descriptors"> <tt class="descname">all_orm_descriptors</tt><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.all_orm_descriptors" title="Permalink to this definition">¶</a></dt> <dd><p>A namespace of all <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces._InspectionAttr" title="sqlalchemy.orm.interfaces._InspectionAttr"><tt class="xref py py-class docutils literal"><span class="pre">_InspectionAttr</span></tt></a> attributes associated with the mapped class.</p> <p>These attributes are in all cases Python <a class="reference internal" href="../glossary.html#term-descriptors"><em class="xref std std-term">descriptors</em></a> associated with the mapped class or its superclasses.</p> <p>This namespace includes attributes that are mapped to the class as well as attributes declared by extension modules. It includes any Python descriptor type that inherits from <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces._InspectionAttr" title="sqlalchemy.orm.interfaces._InspectionAttr"><tt class="xref py py-class docutils literal"><span class="pre">_InspectionAttr</span></tt></a>. This includes <a class="reference internal" href="internals.html#sqlalchemy.orm.attributes.QueryableAttribute" title="sqlalchemy.orm.attributes.QueryableAttribute"><tt class="xref py py-class docutils literal"><span class="pre">QueryableAttribute</span></tt></a>, as well as extension types such as <a class="reference internal" href="extensions/hybrid.html#sqlalchemy.ext.hybrid.hybrid_property" title="sqlalchemy.ext.hybrid.hybrid_property"><tt class="xref py py-class docutils literal"><span class="pre">hybrid_property</span></tt></a>, <a class="reference internal" href="extensions/hybrid.html#sqlalchemy.ext.hybrid.hybrid_method" title="sqlalchemy.ext.hybrid.hybrid_method"><tt class="xref py py-class docutils literal"><span class="pre">hybrid_method</span></tt></a> and <a class="reference internal" href="extensions/associationproxy.html#sqlalchemy.ext.associationproxy.AssociationProxy" title="sqlalchemy.ext.associationproxy.AssociationProxy"><tt class="xref py py-class docutils literal"><span class="pre">AssociationProxy</span></tt></a>.</p> <p>To distinguish between mapped attributes and extension attributes, the attribute <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces._InspectionAttr.extension_type" title="sqlalchemy.orm.interfaces._InspectionAttr.extension_type"><tt class="xref py py-attr docutils literal"><span class="pre">_InspectionAttr.extension_type</span></tt></a> will refer to a constant that distinguishes between different extension types.</p> <p>When dealing with a <a class="reference internal" href="internals.html#sqlalchemy.orm.attributes.QueryableAttribute" title="sqlalchemy.orm.attributes.QueryableAttribute"><tt class="xref py py-class docutils literal"><span class="pre">QueryableAttribute</span></tt></a>, the <a class="reference internal" href="internals.html#sqlalchemy.orm.attributes.QueryableAttribute.property" title="sqlalchemy.orm.attributes.QueryableAttribute.property"><tt class="xref py py-attr docutils literal"><span class="pre">QueryableAttribute.property</span></tt></a> attribute refers to the <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces.MapperProperty" title="sqlalchemy.orm.interfaces.MapperProperty"><tt class="xref py py-class docutils literal"><span class="pre">MapperProperty</span></tt></a> property, which is what you get when referring to the collection of mapped properties via <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.attrs" title="sqlalchemy.orm.mapper.Mapper.attrs"><tt class="xref py py-attr docutils literal"><span class="pre">Mapper.attrs</span></tt></a>.</p> <div class="versionadded"> <p><span>New in version 0.8.0.</span></p> </div> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.attrs" title="sqlalchemy.orm.mapper.Mapper.attrs"><tt class="xref py py-attr docutils literal"><span class="pre">Mapper.attrs</span></tt></a></p> </div> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.attrs"> <tt class="descname">attrs</tt><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.attrs" title="Permalink to this definition">¶</a></dt> <dd><p>A namespace of all <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces.MapperProperty" title="sqlalchemy.orm.interfaces.MapperProperty"><tt class="xref py py-class docutils literal"><span class="pre">MapperProperty</span></tt></a> objects associated this mapper.</p> <p>This is an object that provides each property based on its key name. For instance, the mapper for a <tt class="docutils literal"><span class="pre">User</span></tt> class which has <tt class="docutils literal"><span class="pre">User.name</span></tt> attribute would provide <tt class="docutils literal"><span class="pre">mapper.attrs.name</span></tt>, which would be the <a class="reference internal" href="internals.html#sqlalchemy.orm.properties.ColumnProperty" title="sqlalchemy.orm.properties.ColumnProperty"><tt class="xref py py-class docutils literal"><span class="pre">ColumnProperty</span></tt></a> representing the <tt class="docutils literal"><span class="pre">name</span></tt> column. The namespace object can also be iterated, which would yield each <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces.MapperProperty" title="sqlalchemy.orm.interfaces.MapperProperty"><tt class="xref py py-class docutils literal"><span class="pre">MapperProperty</span></tt></a>.</p> <p><a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> has several pre-filtered views of this attribute which limit the types of properties returned, inclding <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.synonyms" title="sqlalchemy.orm.mapper.Mapper.synonyms"><tt class="xref py py-attr docutils literal"><span class="pre">synonyms</span></tt></a>, <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.column_attrs" title="sqlalchemy.orm.mapper.Mapper.column_attrs"><tt class="xref py py-attr docutils literal"><span class="pre">column_attrs</span></tt></a>, <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.relationships" title="sqlalchemy.orm.mapper.Mapper.relationships"><tt class="xref py py-attr docutils literal"><span class="pre">relationships</span></tt></a>, and <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.composites" title="sqlalchemy.orm.mapper.Mapper.composites"><tt class="xref py py-attr docutils literal"><span class="pre">composites</span></tt></a>.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.all_orm_descriptors" title="sqlalchemy.orm.mapper.Mapper.all_orm_descriptors"><tt class="xref py py-attr docutils literal"><span class="pre">Mapper.all_orm_descriptors</span></tt></a></p> </div> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.base_mapper"> <tt class="descname">base_mapper</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.base_mapper" title="Permalink to this definition">¶</a></dt> <dd><p>The base-most <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> in an inheritance chain.</p> <p>In a non-inheriting scenario, this attribute will always be this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a>. In an inheritance scenario, it references the <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> which is parent to all other <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> objects in the inheritance chain.</p> <p>This is a <em>read only</em> attribute determined during mapper construction. Behavior is undefined if directly modified.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.c"> <tt class="descname">c</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.c" title="Permalink to this definition">¶</a></dt> <dd><p>A synonym for <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.columns" title="sqlalchemy.orm.mapper.Mapper.columns"><tt class="xref py py-attr docutils literal"><span class="pre">columns</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.cascade_iterator"> <tt class="descname">cascade_iterator</tt><big>(</big><em>type_</em>, <em>state</em>, <em>halt_on=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.cascade_iterator" title="Permalink to this definition">¶</a></dt> <dd><p>Iterate each element and its mapper in an object graph, for all relationships that meet the given cascade rule.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><span class="target" id="sqlalchemy.orm.mapper.Mapper.cascade_iterator.params.type_"></span><strong>type_</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.Mapper.cascade_iterator.params.type_">¶</a> – The name of the cascade rule (i.e. save-update, delete, etc.)</li> <li><span class="target" id="sqlalchemy.orm.mapper.Mapper.cascade_iterator.params.state"></span><strong>state</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.Mapper.cascade_iterator.params.state">¶</a> – The lead InstanceState. child items will be processed per the relationships defined for this object’s mapper.</li> </ul> </td> </tr> </tbody> </table> <p>the return value are object instances; this provides a strong reference so that they don’t fall out of scope immediately.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.class_"> <tt class="descname">class_</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.class_" title="Permalink to this definition">¶</a></dt> <dd><p>The Python class which this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> maps.</p> <p>This is a <em>read only</em> attribute determined during mapper construction. Behavior is undefined if directly modified.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.class_manager"> <tt class="descname">class_manager</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.class_manager" title="Permalink to this definition">¶</a></dt> <dd><p>The <a class="reference internal" href="internals.html#sqlalchemy.orm.instrumentation.ClassManager" title="sqlalchemy.orm.instrumentation.ClassManager"><tt class="xref py py-class docutils literal"><span class="pre">ClassManager</span></tt></a> which maintains event listeners and class-bound descriptors for this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a>.</p> <p>This is a <em>read only</em> attribute determined during mapper construction. Behavior is undefined if directly modified.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.column_attrs"> <tt class="descname">column_attrs</tt><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.column_attrs" title="Permalink to this definition">¶</a></dt> <dd><p>Return a namespace of all <a class="reference internal" href="internals.html#sqlalchemy.orm.properties.ColumnProperty" title="sqlalchemy.orm.properties.ColumnProperty"><tt class="xref py py-class docutils literal"><span class="pre">ColumnProperty</span></tt></a> properties maintained by this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a>.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.attrs" title="sqlalchemy.orm.mapper.Mapper.attrs"><tt class="xref py py-attr docutils literal"><span class="pre">Mapper.attrs</span></tt></a> - namespace of all <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces.MapperProperty" title="sqlalchemy.orm.interfaces.MapperProperty"><tt class="xref py py-class docutils literal"><span class="pre">MapperProperty</span></tt></a> objects.</p> </div> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.columns"> <tt class="descname">columns</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.columns" title="Permalink to this definition">¶</a></dt> <dd><p>A collection of <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> or other scalar expression objects maintained by this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a>.</p> <p>The collection behaves the same as that of the <tt class="docutils literal"><span class="pre">c</span></tt> attribute on any <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> object, except that only those columns included in this mapping are present, and are keyed based on the attribute name defined in the mapping, not necessarily the <tt class="docutils literal"><span class="pre">key</span></tt> attribute of the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> itself. Additionally, scalar expressions mapped by <a class="reference internal" href="#sqlalchemy.orm.column_property" title="sqlalchemy.orm.column_property"><tt class="xref py py-func docutils literal"><span class="pre">column_property()</span></tt></a> are also present here.</p> <p>This is a <em>read only</em> attribute determined during mapper construction. Behavior is undefined if directly modified.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.common_parent"> <tt class="descname">common_parent</tt><big>(</big><em>other</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.common_parent" title="Permalink to this definition">¶</a></dt> <dd><p>Return true if the given mapper shares a common inherited parent as this mapper.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.compile"> <tt class="descname">compile</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.compile" title="Permalink to this definition">¶</a></dt> <dd><p>Initialize the inter-mapper relationships of all mappers that</p> <div class="deprecated"> <p><span>Deprecated since version 0.7: </span><a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.compile" title="sqlalchemy.orm.mapper.Mapper.compile"><tt class="xref py py-meth docutils literal"><span class="pre">Mapper.compile()</span></tt></a> is replaced by <a class="reference internal" href="#sqlalchemy.orm.configure_mappers" title="sqlalchemy.orm.configure_mappers"><tt class="xref py py-func docutils literal"><span class="pre">configure_mappers()</span></tt></a></p> </div> <p>have been constructed thus far.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.compiled"> <tt class="descname">compiled</tt><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.compiled" title="Permalink to this definition">¶</a></dt> <dd><div class="deprecated"> <p><span>Deprecated since version 0.7: </span><a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.compiled" title="sqlalchemy.orm.mapper.Mapper.compiled"><tt class="xref py py-attr docutils literal"><span class="pre">Mapper.compiled</span></tt></a> is replaced by <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.configured" title="sqlalchemy.orm.mapper.Mapper.configured"><tt class="xref py py-attr docutils literal"><span class="pre">Mapper.configured</span></tt></a></p> </div> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.composites"> <tt class="descname">composites</tt><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.composites" title="Permalink to this definition">¶</a></dt> <dd><p>Return a namespace of all <a class="reference internal" href="internals.html#sqlalchemy.orm.descriptor_props.CompositeProperty" title="sqlalchemy.orm.descriptor_props.CompositeProperty"><tt class="xref py py-class docutils literal"><span class="pre">CompositeProperty</span></tt></a> properties maintained by this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a>.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.attrs" title="sqlalchemy.orm.mapper.Mapper.attrs"><tt class="xref py py-attr docutils literal"><span class="pre">Mapper.attrs</span></tt></a> - namespace of all <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces.MapperProperty" title="sqlalchemy.orm.interfaces.MapperProperty"><tt class="xref py py-class docutils literal"><span class="pre">MapperProperty</span></tt></a> objects.</p> </div> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.concrete"> <tt class="descname">concrete</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.concrete" title="Permalink to this definition">¶</a></dt> <dd><p>Represent <tt class="docutils literal"><span class="pre">True</span></tt> if this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> is a concrete inheritance mapper.</p> <p>This is a <em>read only</em> attribute determined during mapper construction. Behavior is undefined if directly modified.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.configured"> <tt class="descname">configured</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.configured" title="Permalink to this definition">¶</a></dt> <dd><p>Represent <tt class="docutils literal"><span class="pre">True</span></tt> if this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> has been configured.</p> <p>This is a <em>read only</em> attribute determined during mapper construction. Behavior is undefined if directly modified.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="#sqlalchemy.orm.configure_mappers" title="sqlalchemy.orm.configure_mappers"><tt class="xref py py-func docutils literal"><span class="pre">configure_mappers()</span></tt></a>.</p> </div> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.entity"> <tt class="descname">entity</tt><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.entity" title="Permalink to this definition">¶</a></dt> <dd><p>Part of the inspection API.</p> <p>Returns self.class_.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.get_property"> <tt class="descname">get_property</tt><big>(</big><em>key</em>, <em>_configure_mappers=True</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.get_property" title="Permalink to this definition">¶</a></dt> <dd><p>return a MapperProperty associated with the given key.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.get_property_by_column"> <tt class="descname">get_property_by_column</tt><big>(</big><em>column</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.get_property_by_column" title="Permalink to this definition">¶</a></dt> <dd><p>Given a <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> object, return the <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces.MapperProperty" title="sqlalchemy.orm.interfaces.MapperProperty"><tt class="xref py py-class docutils literal"><span class="pre">MapperProperty</span></tt></a> which maps this column.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.identity_key_from_instance"> <tt class="descname">identity_key_from_instance</tt><big>(</big><em>instance</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.identity_key_from_instance" title="Permalink to this definition">¶</a></dt> <dd><p>Return the identity key for the given instance, based on its primary key attributes.</p> <p>If the instance’s state is expired, calling this method will result in a database check to see if the object has been deleted. If the row no longer exists, <a class="reference internal" href="exceptions.html#sqlalchemy.orm.exc.ObjectDeletedError" title="sqlalchemy.orm.exc.ObjectDeletedError"><tt class="xref py py-class docutils literal"><span class="pre">ObjectDeletedError</span></tt></a> is raised.</p> <p>This value is typically also found on the instance state under the attribute name <cite>key</cite>.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.identity_key_from_primary_key"> <tt class="descname">identity_key_from_primary_key</tt><big>(</big><em>primary_key</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.identity_key_from_primary_key" title="Permalink to this definition">¶</a></dt> <dd><p>Return an identity-map key for use in storing/retrieving an item from an identity map.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><span class="target" id="sqlalchemy.orm.mapper.Mapper.identity_key_from_primary_key.params.primary_key"></span><strong>primary_key</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.Mapper.identity_key_from_primary_key.params.primary_key">¶</a> – A list of values indicating the identifier.</td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.identity_key_from_row"> <tt class="descname">identity_key_from_row</tt><big>(</big><em>row</em>, <em>adapter=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.identity_key_from_row" title="Permalink to this definition">¶</a></dt> <dd><p>Return an identity-map key for use in storing/retrieving an item from the identity map.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><span class="target" id="sqlalchemy.orm.mapper.Mapper.identity_key_from_row.params.row"></span><strong>row</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.orm.mapper.Mapper.identity_key_from_row.params.row">¶</a> – A <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.RowProxy" title="sqlalchemy.engine.RowProxy"><tt class="xref py py-class docutils literal"><span class="pre">RowProxy</span></tt></a> instance. The columns which are mapped by this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> should be locatable in the row, preferably via the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> object directly (as is the case when a <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.select" title="sqlalchemy.sql.expression.select"><tt class="xref py py-func docutils literal"><span class="pre">select()</span></tt></a> construct is executed), or via string names of the form <tt class="docutils literal"><span class="pre"><tablename>_<colname></span></tt>.</td> </tr> </tbody> </table> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.inherits"> <tt class="descname">inherits</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.inherits" title="Permalink to this definition">¶</a></dt> <dd><p>References the <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> which this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> inherits from, if any.</p> <p>This is a <em>read only</em> attribute determined during mapper construction. Behavior is undefined if directly modified.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.is_mapper"> <tt class="descname">is_mapper</tt><em class="property"> = True</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.is_mapper" title="Permalink to this definition">¶</a></dt> <dd><p>Part of the inspection API.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.isa"> <tt class="descname">isa</tt><big>(</big><em>other</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.isa" title="Permalink to this definition">¶</a></dt> <dd><p>Return True if the this mapper inherits from the given mapper.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.iterate_properties"> <tt class="descname">iterate_properties</tt><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.iterate_properties" title="Permalink to this definition">¶</a></dt> <dd><p>return an iterator of all MapperProperty objects.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.local_table"> <tt class="descname">local_table</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.local_table" title="Permalink to this definition">¶</a></dt> <dd><p>The <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.Selectable" title="sqlalchemy.sql.expression.Selectable"><tt class="xref py py-class docutils literal"><span class="pre">Selectable</span></tt></a> which this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> manages.</p> <p>Typically is an instance of <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> or <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.Alias" title="sqlalchemy.sql.expression.Alias"><tt class="xref py py-class docutils literal"><span class="pre">Alias</span></tt></a>. May also be <tt class="docutils literal"><span class="pre">None</span></tt>.</p> <p>The “local” table is the selectable that the <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> is directly responsible for managing from an attribute access and flush perspective. For non-inheriting mappers, the local table is the same as the “mapped” table. For joined-table inheritance mappers, local_table will be the particular sub-table of the overall “join” which this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> represents. If this mapper is a single-table inheriting mapper, local_table will be <tt class="docutils literal"><span class="pre">None</span></tt>.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.mapped_table" title="sqlalchemy.orm.mapper.Mapper.mapped_table"><tt class="xref py py-attr docutils literal"><span class="pre">mapped_table</span></tt></a>.</p> </div> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.mapped_table"> <tt class="descname">mapped_table</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.mapped_table" title="Permalink to this definition">¶</a></dt> <dd><p>The <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.Selectable" title="sqlalchemy.sql.expression.Selectable"><tt class="xref py py-class docutils literal"><span class="pre">Selectable</span></tt></a> to which this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> is mapped.</p> <p>Typically an instance of <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a>, <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.Join" title="sqlalchemy.sql.expression.Join"><tt class="xref py py-class docutils literal"><span class="pre">Join</span></tt></a>, or <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.Alias" title="sqlalchemy.sql.expression.Alias"><tt class="xref py py-class docutils literal"><span class="pre">Alias</span></tt></a>.</p> <p>The “mapped” table is the selectable that the mapper selects from during queries. For non-inheriting mappers, the mapped table is the same as the “local” table. For joined-table inheritance mappers, mapped_table references the full <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.Join" title="sqlalchemy.sql.expression.Join"><tt class="xref py py-class docutils literal"><span class="pre">Join</span></tt></a> representing full rows for this particular subclass. For single-table inheritance mappers, mapped_table references the base table.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.local_table" title="sqlalchemy.orm.mapper.Mapper.local_table"><tt class="xref py py-attr docutils literal"><span class="pre">local_table</span></tt></a>.</p> </div> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.mapper"> <tt class="descname">mapper</tt><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.mapper" title="Permalink to this definition">¶</a></dt> <dd><p>Part of the inspection API.</p> <p>Returns self.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.non_primary"> <tt class="descname">non_primary</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.non_primary" title="Permalink to this definition">¶</a></dt> <dd><p>Represent <tt class="docutils literal"><span class="pre">True</span></tt> if this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> is a “non-primary” mapper, e.g. a mapper that is used only to selet rows but not for persistence management.</p> <p>This is a <em>read only</em> attribute determined during mapper construction. Behavior is undefined if directly modified.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.polymorphic_identity"> <tt class="descname">polymorphic_identity</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.polymorphic_identity" title="Permalink to this definition">¶</a></dt> <dd><p>Represent an identifier which is matched against the <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.polymorphic_on" title="sqlalchemy.orm.mapper.Mapper.polymorphic_on"><tt class="xref py py-attr docutils literal"><span class="pre">polymorphic_on</span></tt></a> column during result row loading.</p> <p>Used only with inheritance, this object can be of any type which is comparable to the type of column represented by <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.polymorphic_on" title="sqlalchemy.orm.mapper.Mapper.polymorphic_on"><tt class="xref py py-attr docutils literal"><span class="pre">polymorphic_on</span></tt></a>.</p> <p>This is a <em>read only</em> attribute determined during mapper construction. Behavior is undefined if directly modified.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.polymorphic_iterator"> <tt class="descname">polymorphic_iterator</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.polymorphic_iterator" title="Permalink to this definition">¶</a></dt> <dd><p>Iterate through the collection including this mapper and all descendant mappers.</p> <p>This includes not just the immediately inheriting mappers but all their inheriting mappers as well.</p> <p>To iterate through an entire hierarchy, use <tt class="docutils literal"><span class="pre">mapper.base_mapper.polymorphic_iterator()</span></tt>.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.polymorphic_map"> <tt class="descname">polymorphic_map</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.polymorphic_map" title="Permalink to this definition">¶</a></dt> <dd><p>A mapping of “polymorphic identity” identifiers mapped to <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> instances, within an inheritance scenario.</p> <p>The identifiers can be of any type which is comparable to the type of column represented by <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.polymorphic_on" title="sqlalchemy.orm.mapper.Mapper.polymorphic_on"><tt class="xref py py-attr docutils literal"><span class="pre">polymorphic_on</span></tt></a>.</p> <p>An inheritance chain of mappers will all reference the same polymorphic map object. The object is used to correlate incoming result rows to target mappers.</p> <p>This is a <em>read only</em> attribute determined during mapper construction. Behavior is undefined if directly modified.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.polymorphic_on"> <tt class="descname">polymorphic_on</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.polymorphic_on" title="Permalink to this definition">¶</a></dt> <dd><p>The <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> or SQL expression specified as the <tt class="docutils literal"><span class="pre">polymorphic_on</span></tt> argument for this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a>, within an inheritance scenario.</p> <p>This attribute is normally a <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Column" title="sqlalchemy.schema.Column"><tt class="xref py py-class docutils literal"><span class="pre">Column</span></tt></a> instance but may also be an expression, such as one derived from <a class="reference internal" href="../core/sqlelement.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>.</p> <p>This is a <em>read only</em> attribute determined during mapper construction. Behavior is undefined if directly modified.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.primary_key"> <tt class="descname">primary_key</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.primary_key" title="Permalink to this definition">¶</a></dt> <dd><p>An iterable containing the collection of <a class="reference internal" href="../core/metadata.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 comprise the ‘primary key’ of the mapped table, from the perspective of this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a>.</p> <p>This list is against the selectable in <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.mapped_table" title="sqlalchemy.orm.mapper.Mapper.mapped_table"><tt class="xref py py-attr docutils literal"><span class="pre">mapped_table</span></tt></a>. In the case of inheriting mappers, some columns may be managed by a superclass mapper. For example, in the case of a <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.Join" title="sqlalchemy.sql.expression.Join"><tt class="xref py py-class docutils literal"><span class="pre">Join</span></tt></a>, the primary key is determined by all of the primary key columns across all tables referenced by the <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.Join" title="sqlalchemy.sql.expression.Join"><tt class="xref py py-class docutils literal"><span class="pre">Join</span></tt></a>.</p> <p>The list is also not necessarily the same as the primary key column collection associated with the underlying tables; the <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> features a <tt class="docutils literal"><span class="pre">primary_key</span></tt> argument that can override what the <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> considers as primary key columns.</p> <p>This is a <em>read only</em> attribute determined during mapper construction. Behavior is undefined if directly modified.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.primary_key_from_instance"> <tt class="descname">primary_key_from_instance</tt><big>(</big><em>instance</em><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.primary_key_from_instance" title="Permalink to this definition">¶</a></dt> <dd><p>Return the list of primary key values for the given instance.</p> <p>If the instance’s state is expired, calling this method will result in a database check to see if the object has been deleted. If the row no longer exists, <a class="reference internal" href="exceptions.html#sqlalchemy.orm.exc.ObjectDeletedError" title="sqlalchemy.orm.exc.ObjectDeletedError"><tt class="xref py py-class docutils literal"><span class="pre">ObjectDeletedError</span></tt></a> is raised.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.orm.mapper.Mapper.primary_mapper"> <tt class="descname">primary_mapper</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.primary_mapper" title="Permalink to this definition">¶</a></dt> <dd><p>Return the primary mapper corresponding to this mapper’s class key (class).</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.relationships"> <tt class="descname">relationships</tt><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.relationships" title="Permalink to this definition">¶</a></dt> <dd><p>Return a namespace of all <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> properties maintained by this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a>.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.attrs" title="sqlalchemy.orm.mapper.Mapper.attrs"><tt class="xref py py-attr docutils literal"><span class="pre">Mapper.attrs</span></tt></a> - namespace of all <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces.MapperProperty" title="sqlalchemy.orm.interfaces.MapperProperty"><tt class="xref py py-class docutils literal"><span class="pre">MapperProperty</span></tt></a> objects.</p> </div> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.selectable"> <tt class="descname">selectable</tt><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.selectable" title="Permalink to this definition">¶</a></dt> <dd><p>The <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.select" title="sqlalchemy.sql.expression.select"><tt class="xref py py-func docutils literal"><span class="pre">select()</span></tt></a> construct this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> selects from by default.</p> <p>Normally, this is equivalent to <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.mapped_table" title="sqlalchemy.orm.mapper.Mapper.mapped_table"><tt class="xref py py-attr docutils literal"><span class="pre">mapped_table</span></tt></a>, unless the <tt class="docutils literal"><span class="pre">with_polymorphic</span></tt> feature is in use, in which case the full “polymorphic” selectable is returned.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.self_and_descendants"> <tt class="descname">self_and_descendants</tt><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.self_and_descendants" title="Permalink to this definition">¶</a></dt> <dd><p>The collection including this mapper and all descendant mappers.</p> <p>This includes not just the immediately inheriting mappers but all their inheriting mappers as well.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.single"> <tt class="descname">single</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.single" title="Permalink to this definition">¶</a></dt> <dd><p>Represent <tt class="docutils literal"><span class="pre">True</span></tt> if this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> is a single table inheritance mapper.</p> <p><a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.local_table" title="sqlalchemy.orm.mapper.Mapper.local_table"><tt class="xref py py-attr docutils literal"><span class="pre">local_table</span></tt></a> will be <tt class="docutils literal"><span class="pre">None</span></tt> if this flag is set.</p> <p>This is a <em>read only</em> attribute determined during mapper construction. Behavior is undefined if directly modified.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.synonyms"> <tt class="descname">synonyms</tt><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.synonyms" title="Permalink to this definition">¶</a></dt> <dd><p>Return a namespace of all <a class="reference internal" href="internals.html#sqlalchemy.orm.descriptor_props.SynonymProperty" title="sqlalchemy.orm.descriptor_props.SynonymProperty"><tt class="xref py py-class docutils literal"><span class="pre">SynonymProperty</span></tt></a> properties maintained by this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a>.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper.attrs" title="sqlalchemy.orm.mapper.Mapper.attrs"><tt class="xref py py-attr docutils literal"><span class="pre">Mapper.attrs</span></tt></a> - namespace of all <a class="reference internal" href="internals.html#sqlalchemy.orm.interfaces.MapperProperty" title="sqlalchemy.orm.interfaces.MapperProperty"><tt class="xref py py-class docutils literal"><span class="pre">MapperProperty</span></tt></a> objects.</p> </div> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.tables"> <tt class="descname">tables</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.tables" title="Permalink to this definition">¶</a></dt> <dd><p>An iterable containing the collection of <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> objects which this <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> is aware of.</p> <p>If the mapper is mapped to a <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.Join" title="sqlalchemy.sql.expression.Join"><tt class="xref py py-class docutils literal"><span class="pre">Join</span></tt></a>, or an <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.Alias" title="sqlalchemy.sql.expression.Alias"><tt class="xref py py-class docutils literal"><span class="pre">Alias</span></tt></a> representing a <a class="reference internal" href="../core/selectable.html#sqlalchemy.sql.expression.Select" title="sqlalchemy.sql.expression.Select"><tt class="xref py py-class docutils literal"><span class="pre">Select</span></tt></a>, the individual <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><tt class="xref py py-class docutils literal"><span class="pre">Table</span></tt></a> objects that comprise the full construct will be represented here.</p> <p>This is a <em>read only</em> attribute determined during mapper construction. Behavior is undefined if directly modified.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.validators"> <tt class="descname">validators</tt><em class="property"> = None</em><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.validators" title="Permalink to this definition">¶</a></dt> <dd><p>An immutable dictionary of attributes which have been decorated using the <a class="reference internal" href="#sqlalchemy.orm.validates" title="sqlalchemy.orm.validates"><tt class="xref py py-func docutils literal"><span class="pre">validates()</span></tt></a> decorator.</p> <p>The dictionary contains string attribute names as keys mapped to the actual validation method.</p> </dd></dl> <dl class="attribute"> <dt id="sqlalchemy.orm.mapper.Mapper.with_polymorphic_mappers"> <tt class="descname">with_polymorphic_mappers</tt><a class="headerlink" href="#sqlalchemy.orm.mapper.Mapper.with_polymorphic_mappers" title="Permalink to this definition">¶</a></dt> <dd><p>The list of <a class="reference internal" href="#sqlalchemy.orm.mapper.Mapper" title="sqlalchemy.orm.mapper.Mapper"><tt class="xref py py-class docutils literal"><span class="pre">Mapper</span></tt></a> objects included in the default “polymorphic” query.</p> </dd></dl> </dd></dl> </div> </div> </div> </div> <div id="docs-bottom-navigation" class="docs-navigation-links"> Previous: <a href="tutorial.html" title="previous chapter">Object Relational Tutorial</a> Next: <a href="relationships.html" title="next chapter">Relationship Configuration</a> <div id="docs-copyright"> © <a href="../copyright.html">Copyright</a> 2007-2014, the SQLAlchemy authors and contributors. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2b1. </div> </div> </div> </body> </html>