因此,使用SqlAlchemy,我在用户模型和评论模型之间创建了一个相当简单的多对多关系。
users.py
class UsersModel(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String(50))
email = Column(String(50))
issues = relationship(IssuesModel, backref="user")
comments = relationship(IssueCommentsModel, backref="user")
voted_comments = association_proxy('users_comments', 'comment')
def __init__(self, **fields):
self.__dict__.update(fields)
def __repr__(self):
return "<Users('%s', '%s', '%s')>" % (self.id,
self.username,
self.email)
users_comments.py
class UsersCommentsModel(Base):
__tablename__ = 'users_comments'
user_id = Column(Integer, ForeignKey('users.id'), primary_key=True)
comment_id = Column(Integer, ForeignKey('issue_comments.id'), primary_key=True)
vote = Column(Integer(1))
user = relationship(UsersModel,
backref="users_comments")
comment = relationship(IssueCommentsModel,
backref="users_comments")
def __init__(self, **fields):
self.__dict__.update(fields)
def __repr__(self):
return "<UsersComments('%s', '%s', '%s')>" % (self.user_id,
self.comment_id,
self.vote)
issue_comments.py
class IssueCommentsModel(Base):
__tablename__ = 'issue_comments'
id = Column(Integer, primary_key=True)
body = Column(String(300))
created = Column(DateTime)
change_time = Column(DateTime)
score = Column(Integer(100), default=0)
issue_id = Column(Integer, ForeignKey('issues.id'))
user_id = Column(Integer, ForeignKey('users.id'))
voted_users = association_proxy('users_comments', 'user')
def __init__(self, **fields):
self.__dict__.update(fields)
def __repr__(self):
return "<IssueComments('%s', '%s', '%s', '%s', '%s', '%s')>" % (self.id,
self.body,
self.issue,
self.user,
self.created,
self.change_time)
每个用户都可以创建评论,并向上/向下投票。上面的代码是完全可用的代码。我的问题是这个。当我删除UsersCommentsModel类中的两个backref时,代码不再起作用并抛出InvalidRequestError。它指出在UsersModel映射器上找不到users_comments属性。我认为这很奇怪,b / c我认为你可以通过中央users_comments关系模型代理所有关系,而不必在用户/评论模型中实际存储该模型的实例。
有没有办法删除backrefs,所以没有其他属性存储在用户/评论模型中?