Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8376463
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T15:26:17+00:00 2026-06-09T15:26:17+00:00

I am testing out setting up SQLAlchemy to map an existing database. This database

  • 0

I am testing out setting up SQLAlchemy to map an existing database. This database was set up a long time ago, automatically, by a previous 3rd party application which we are no longer using, so some expected things like foreign key constraints are not defined. The software would manage all of those relationships.

It is a node-ish type production tracking database structure, with parent-child relationships. The nodetype-specific data lives in their own tables, and there is a main relationship table for the common columns like type, uid, parentUid, …

The structure is like this…

  1. A hierarchy table that contains basically every node entry, with a primary key “uid”, a “type” enum, and a “parentUid” to reference a parent node.
  2. NodeA / NodeB / … table has a “uid” that one-to-one matches the hierarchy table

What I have gathered from the SQLAlchemy docs is that I should try to do “join” tables. Here is what I have so far:

# has a column called 'parentUid'
hierarchy = Table('hierarchy', METADATA, autoload=True)

hier_fk = lambda: Column('uid', 
                          Integer, 
                          ForeignKey('hierarchy.uid'), 
                          primary_key=True)

nodeTypeA = Table('nodetype_a', METADATA, nodehier_fk(), autoload=True)
nodeTypeB = Table('nodetype_b', METADATA, nodehier_fk(), autoload=True)

Base = declarative_base()

class NodeA(Base):
    __table__ = join(hierarchy, nodeTypeA)

    id = column_property(hierarchy.c.uid, nodeTypeA.c.uid)
    uid = nodeTypeA.c.uid


class NodeB(Base):
    __table__ = join(hierarchy, nodeTypeB)

    id = column_property(hierarchy.c.uid, nodeTypeB.c.uid)
    uid = nodeTypeB.c.uid

    # cannot figure this one out
    parent = relationship("NodeA", primaryjoin="NodeB.parentUid==NodeA.id")

The relationship is clearly wrong and crashes. I have tried a bunch of combinations of defining the foreign_keys attributes, and using a mixture of the hierarchy.c.uid style approaches. But I just can’t grasp how to make the relationship to this other table.

Without the relationship line, the queries work great. I get the full representation of each Node joined on the hierarchy table. I can even manually get the NodeA parent of NodeB by doing:

node_a = session.query(NodeA).filter_by(uid=node_b.parentUid).first()

Is the “join” approach appropriate for my goal? How can I get this relationship working?

Update

I have managed to get a one-way relationship working so far with the following:

children = relationship("NodeB", 
                        primaryjoin="NodeB.parentUid==NodeA.id", 
                        foreign_keys=[hierarchy.c.parentUid],
                        # backref="parent"
            )

But if I uncomment the backref to have it put the reverse on NodeB, I get this:

ArgumentError: NodeA.children and back-reference NodeB.parent are both
of the same direction . Did you mean to set
remote_side on the many-to-one side ?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T15:26:18+00:00Added an answer on June 9, 2026 at 3:26 pm

    remote_side is used in self-referential relationships to distinguish which side is “remote”. The flag is described in http://docs.sqlalchemy.org/en/latest/orm/relationships.html#adjacency-list-relationships. Because you’re mapping classes directly to a join(), SQLAlchemy considers each join() to be the mapped table, and the “is self referential” condition is detected because both joins depend on the same base table. If you were to build this mapping using the usual pattern of joined table inheritance (see http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#joined-table-inheritance), the relationship() would have a little more context with which to figure out how to join without the explicit remote_side argument.

    Full example using the given approach:

    from sqlalchemy import *
    from sqlalchemy.orm import *
    from sqlalchemy.ext.declarative import declarative_base
    
    e = create_engine("sqlite://", echo=True)
    
    e.execute("""
    create table hierarchy (uid int primary key, parentUid int)
    """)
    
    e.execute("""
    create table nodetype_a (uid int primary key)
    """)
    
    e.execute("""
    create table nodetype_b (uid int primary key)
    """)
    
    Base = declarative_base()
    
    
    # has a column called 'parentUid'
    hierarchy = Table('hierarchy', Base.metadata, autoload=True, autoload_with=e)
    
    nodehier_fk = lambda: Column('uid',
                              Integer,
                              ForeignKey('hierarchy.uid'),
                              primary_key=True)
    
    nodeTypeA = Table('nodetype_a', Base.metadata, nodehier_fk(), autoload=True, autoload_with=e)
    nodeTypeB = Table('nodetype_b', Base.metadata, nodehier_fk(), autoload=True, autoload_with=e)
    
    Base = declarative_base()
    
    class NodeA(Base):
        __table__ = join(hierarchy, nodeTypeA)
    
        id = column_property(hierarchy.c.uid, nodeTypeA.c.uid)
        uid = nodeTypeA.c.uid
    
    
    class NodeB(Base):
        __table__ = join(hierarchy, nodeTypeB)
    
        id = column_property(hierarchy.c.uid, nodeTypeB.c.uid)
        uid = nodeTypeB.c.uid
    
        # cannot figure this one out
        parent = relationship("NodeA",
                        primaryjoin="NodeB.parentUid==NodeA.id",
                        foreign_keys=hierarchy.c.parentUid,
                        remote_side=hierarchy.c.uid,
                        backref="children")
    
    s = Session(execute)
    s.add_all([
            NodeA(children=[NodeB(), NodeB()])
    ])
    s.commit()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am testing out IF statements in MySQL for the first time and I
I am testing out the new database project features of Visual Studio 2010 and
Im just testing out JSF 2 with Primefaces and are setting up a basic
Testing out someone elses code, I noticed a few JSP pages printing funky non-ASCII
In testing out our API, one of our testers found out that when they
I'm testing out faults and exception handling on my service and am seeing odd
I was testing out RQ (Redis-Queue) when after running the command rqworker and testing
I'm testing out the OpenERP 6.1 web client, and I sometimes have a sales
i'm just testing out the csv component in python, and i am having some
I am having issues testing out the Scala Parser Combinator functionality for a simple

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.