So using SqlAlchemy, I'm creating a fairly simple many-to-many relationship between a users model and a comments model.
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)
Each user has the ability to both create comments, and either up/down vote them. The above code is completely working code. My question is this. When I remove the two backrefs in the UsersCommentsModel class, the code no longer works and an InvalidRequestError is thrown. It states that the users_comments attribute cannot be found on the UsersModel mapper. I thought this was strange, b/c I would think you would be able to proxy all relationships through the central users_comments relationship model, and never have to actually store an instance of that model in the users/comments models.
Question:
Is there any way to remove the backrefs, so no other attributes are stored in the users/comments models?