42

I have a User table and a Friend table. The Friend table holds two foreign keys both to my User table as well as a status field. I am trying to be able to call attributes from my User table on a Friend object. For example, I would love to be able to do something like, friend.name, or friend.email.

class User(Base):
    """ Holds user info """

    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String(25), unique=True)
    email = Column(String(50), unique=True)
    password = Column(String(25))
    admin = Column(Boolean)

    # relationships
    friends = relationship('Friend', backref='Friend.friend_id',primaryjoin='User.id==Friend.user_id', lazy='dynamic')

class Friend(Base):
    __tablename__ = 'friend'

    user_id = Column(Integer, ForeignKey(User.id), primary_key=True)
    friend_id = Column(Integer, ForeignKey(User.id), primary_key=True)
    request_status = Column(Boolean)

When I get friend objects all I have is the 2 user_ids and i want to display all properties of each user so I can use that information in forms, etc. I am new to sqlalchemy - still trying to learn more advanced features. This is just a snippet from a larger Flask project and this feature is going to be for friend requests, etc. I've tried to look up association objects, etc, but I am having a hard with it.

Any help would be greatly appreciated.

4

1 回答 1

66

首先,如果您使用的是flask-sqlalchemy,为什么要直接使用 sqlalchemy 而不是 Flask 的db.Model

我强烈建议使用flask-sqlalchemy扩展,因为它利用了会话和其他一些简洁的东西。

创建代理便利对象很简单。只需在类中添加与它的关系Friend即可。

class Friend(Base):
    __tablename__ = 'friend'

    user_id = Column(Integer, ForeignKey(User.id), primary_key=True)
    friend_id = Column(Integer, ForeignKey(User.id), primary_key=True)
    request_status = Column(Boolean)

    user = relationship('User', foreign_keys='Friend.user_id')
    friend = relationship('User', foreign_keys='Friend.friend_id')

SQLAlchemy 将负责其余的工作,您可以通过以下方式访问用户对象:

name = friend.user.name

如果您计划user每次使用该对象时都使用该friend对象 lazy='joined',请在relationship. 这样,它将两个对象加载到单个查询中。

于 2013-09-17T16:12:48.497 回答