Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to extend the `getter`-functionality of SQLAlchemy's association_proxy?
    primarykey
    data
    text
    <p><strong>Edit:</strong> I would like to model a <code>1 to 0:1</code> relationship between <code>User</code> and <code>Comment</code> (a User can have zero or one Comment). Instead of accessing the object <code>Comment</code> I would rather directly access the comment itself. Using SQLAlchemys <code>association_proxy</code> works perfect for that scenario <strong>except</strong> for one thing: accessing <code>User.comment</code> before having a <code>Comment</code> associated. But in this case I would rather expect <code>None</code> instead of <code>AttributeError</code> as result.</p> <p>Look at the following example:</p> <pre><code>import sqlalchemy as sa import sqlalchemy.orm as orm from sqlalchemy import Column, Integer, Text, ForeignKey, Table from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.associationproxy import association_proxy Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(Text) def __init__(self, name): self.name = name # proxy the 'comment' attribute from the 'comment_object' relationship comment = association_proxy('comment_object', 'comment') class Comment(Base): __tablename__ = 'comments' id = Column(Integer, primary_key=True) comment = Column('comment', Text, nullable=False, default="") user_id = Column(ForeignKey('users.id'), nullable=False, unique=True) # user_id has to be unique to ensure that a User can not have more than one comments def __init__(self, comment): self.comment = comment user_object = orm.relationship( "User", uselist=False, # added after edditing the question backref=orm.backref('comment_object', uselist=False) ) if __name__ == "__main__": engine = sa.create_engine('sqlite:///:memory:', echo=True) Session = orm.sessionmaker(bind=engine) Base.metadata.create_all(engine) session = Session() </code></pre> <p>Now, the following code throws an <code>AttributeError</code>:</p> <pre><code>u = User(name="Max Mueller") print u.comment </code></pre> <p>What would be the best way to catch that exception and provide a default value instead (like an empty string)?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload