Edit: I would like to simulate a 1 to 0:1 relationship between User and Comment (a user can have zero or one comment). Instead of accessing the Comment object, I would like to directly access the comment itself. Using SQLAlchemys association_proxy great for this scenario except : to access User.comment before linking Comment . But in this case, I would rather expect None instead of AttributeError .
Take a look at the following example:
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
Now the following code throws an AttributeError :
u = User(name="Max Mueller") print u.comment
What would be the best way to catch this exception and instead specify a default value (for example, an empty string)?
source share