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

  • Home
  • SEARCH
  • 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 9181127
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T18:12:46+00:00 2026-06-17T18:12:46+00:00

Starting from an existing (SQLite) database with foreign keys, can SQLAlchemy automatically build relationships

  • 0

Starting from an existing (SQLite) database with foreign keys, can SQLAlchemy automatically build relationships?

SQLAlchemy classes are automatically created via __table_args__ = {'autoload': True}.

The goal would be to easily access data from related tables without having to add all the relationships one by one by hand (i.e. without using sqlalchemy.orm.relationship() and sqlalchemy.orm.backref).

  • 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-17T18:12:47+00:00Added an answer on June 17, 2026 at 6:12 pm

    [Update] As of SQLAlchemy 0.9.1 there is Automap extension for doing that.

    For SQLAlchemy < 0.9.0 it is possible to use sqlalchemy reflection.

    SQLAlchemy reflection loads foreign/primary keys relations between tables. But doesn’t create relations between mapped classes. Actually reflection doesn’t create mapped classes for you – you have to specify mapped class name.

    Actually I think that reflection support for loading foreign keys is a great helper and time saving tool. Using it you can build a query using joins without need to specify which columns to use for a join.

    from sqlalchemy import *
    from sqlalchemy import create_engine, orm
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import relationship
    
    
    
    metadata = MetaData()
    Base = declarative_base()
    Base.metadata = metadata
    
    db = create_engine('<db connection URL>',echo=False)
    metadata.reflect(bind=db)
    
    cause_code_table = metadata.tables['cause_code']
    ndticket_table = metadata.tables['ndticket']
    
    sm = orm.sessionmaker(bind=db, autoflush=True, autocommit=True, expire_on_commit=True)
    session = orm.scoped_session(sm)
    
    q = session.query(ndticket_table,cause_code_table).join(cause_code_table)
    for r in q.limit(10):
        print r
    

    Also when I was using reflection to run queries to existing database – I had to define only mapped classes names, table bindings, relations, BUT there were no need to define table columns for these relations.

    class CauseCode(Base):
        __tablename__ = "cause_code"
    
    class NDTicket(Base):
        __tablename__ = "ndticket"
        cause_code = relationship("CauseCode", backref = "ndticket")
    
    
    q = session.query(NDTicket)
    for r in q.limit(10):
        print r.ticket_id, r.cause_code.cause_code
    

    Overall SQLAlchemy reflection is already powerful tool and save me time, so adding relations manually is a small overhead for me.

    If I would have to develop functionality that will add relations between mapped objects using existing foreign keys, I would start from using reflection with inspector. Using get_foreign_keys() method gives all information required to build relations – referred table name, referred column name and column name in target table. And would use this information for adding property with relationship into mapped class.

    insp = reflection.Inspector.from_engine(db)
    print insp.get_table_names()
    print insp.get_foreign_keys(NDTicket.__tablename__)
    >>>[{'referred_table': u'cause_code', 'referred_columns': [u'cause_code'], 'referred_schema': None, 'name': u'SYS_C00135367', 'constrained_columns': [u'cause_code_id']}]
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

starting from existing fiddle, I've created this sample: http://jsfiddle.net/2DaR6/90/ Here's the html code: <div
Starting from an existing code.google project, and having successfully pushed initial code. I created
How can I remove entries from a list of strings starting from nth position?
Is it tedious to migrate an existing website to DNN? Will starting from scratch
All, We have 300 entity classes that was generated from existing DB schema for
I am coming from VB6 and I am starting to convert an existing VB6
I see that EF can update a model based on an existing database schema.
Starting from scratch with very little knowledge of .NET, how much ASP.NET should I
Starting from scratch is hard. How do you do it? I quite like color
Starting from Visual Studio 2010, iterating over a set seems to return an iterator

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.