Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

python - backref class attribute

How to initialize backrefs of mappers without some queries through a session? For example, I have two models, named "Client" and "Subject" in follow code:

Base = declarative_base()

class Client(Base):
    __tablename__ = "clients"

    id = Column(Integer, primary_key=True)
    created = Column(DateTime, default=datetime.datetime.now)
    name = Column(String)

    subjects = relationship("Subject",  cascade="all,delete",
        backref=backref("client"))


class Subject(Base):
    __tablename__ = "subjects"

    id = Column(Integer, primary_key=True)
    client_id = Column(Integer, ForeignKey(Client.id, ondelete='CASCADE'))

Then, somewhere in my code, I want to get the backref client of the class Subject like this, but that raises an exception:

>>> Subject.client
AttributeError: type object 'Subject' has no attribute 'client'

After a query to Client like:

>>> session.query(Client).first()
>>> Subject.client
<sqlalchemy.orm.attributes.InstrumentedAttribute at 0x43ca1d0>

Attribute client was created after a query to the related model(mapper).
I don't want to make such "warming" queries!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Alternatively, you could use:

from sqlalchemy.orm import configure_mappers

configure_mappers()

This has the advantage that it creates all the backrefs for all your models in one step.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...