B
B
beduin012018-03-12 13:39:40
Python
beduin01, 2018-03-12 13:39:40

How to refer to a model field?

I have two tables:

CREATE TABLE "Users"(
    "id"   Integer PRIMARY KEY,
    "name" Text,
CONSTRAINT "unique_id" UNIQUE ( "id" ) )

CREATE TABLE "addresses"(
    "id"      Integer PRIMARY KEY,
    "email"   Text,
    "user_id" Integer,
    CONSTRAINT "lnk_Users_addresses" FOREIGN KEY ( "user_id" ) REFERENCES "Users"( "id" ), 
CONSTRAINT "unique_id" UNIQUE ( "id" ) )

Here is the code that handles all this:
engine = create_engine('sqlite:///sql_test.db', echo=True)
Session = sessionmaker(bind=engine)
sess = Session()
Base = automap_base()
Base.prepare(engine, reflect=True)
User = Base.classes.Users
addresses = Base.classes.addresses

answer = sess.query(User).filter(User.id==1).first()
print(type(answer)) # class User

If I were writing in a declarative style, then there is a `backref='uuu'` ( link ) feature that I can use to access data from the addresses table. And then how to be?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question