gpt4 book ai didi

python - 如何扩展 SQLAlchemy 的 association_proxy 的 `getter` 功能?

转载 作者:行者123 更新时间:2023-11-28 22:03:29 24 4
gpt4 key购买 nike

编辑:我想为 UserComment 之间的 1 到 0:1 关系建模(一个用户可以有零个或一个评论)。与其访问对象 Comment,不如直接访问评论本身。使用 SQLAlchemys association_proxy 非常适合该场景除了一件事:在关联 Comment 之前访问 User.comment .但在这种情况下,我宁愿期望 None 而不是 AttributeError 作为结果。

看下面的例子:

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()

现在,下面的代码抛出一个AttributeError:

u = User(name="Max Mueller")
print u.comment

捕获该异常并提供默认值(如空字符串)的最佳方法是什么?

最佳答案

为此,您真的不需要 association_proxy。使用常规 property,您真的可以过得很好。 AttributeError(可能)是因为 comment_object 本身是 None,因为没有依赖行,而 None 没有 comment 属性。

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
@property
def comment(self):
if self.comment_object is None:
return ""
else:
return self.comment_object.comment

@comment.setter
def comment(self, value):
if self.comment_object is None:
self.comment_object = Comment()
self.comment_object.comment = value

关于python - 如何扩展 SQLAlchemy 的 association_proxy 的 `getter` 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9063478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com