Flask SqlAlchemy多对多关系只能在按关系名称访问时返回一个结果

时间:2014-12-02 20:39:42

标签: python flask sqlalchemy many-to-many

我有一个简单的多对多关系,使用sql Alchemy这样:

file_favorites = db.Table('file_favorites',
                              db.Column('file_id', db.Integer(), db.ForeignKey('file.id')),
                              db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
                              db.Column('created_at', db.DateTime(), default=db.func.now()))


    class File(db.Model, helpers.ModelMixin):
        id = db.Column(db.Integer, primary_key=True, autoincrement=True)
        name = db.Column(db.Unicode, nullable=False)
        description = db.Column(db.Unicode, nullable=False)
        created_at = db.Column(db.DateTime(), default=func.now())
        last_updated = db.Column(db.DateTime(), default=func.now(), onupdate=func.now())

        user_id = db.Column('user_id', db.Integer(), db.ForeignKey('user.id'), nullable=False, index=True)
        user = db.relationship('User')

        favorited_by = db.relationship('User', secondary=file_favorites, lazy='dynamic')   

        def is_favorite_of(self, user):
            query = File.query
            query = query.join(file_favorites)
            query = query.filter(file_favorites.c.file_id == self.id)
            query = query.filter(file_favorites.c.user_id == user.id)
            return query.count() > 0

        def favorite(self, user):
            if not self.is_favorite_of(user):
                self.favorited_by.append(user)

        def unfavorite(self, user):
            if self.is_favorite_of(user):
                self.favorited_by.remove(user)

我希望访问favorited_by属性会导致查询尝试返回已经收藏此文件的用户列表。但是,似乎查询仅访问FIRST用户以收藏此文件。我对此感到困惑,并期望我没有正确理解sqlalchemy的关系。以下是我遇到的结果:

def create_model(model_class, *args, **kwargs):
    model = model_class(*args, **kwargs)
    db.session.add(model)
    db.session.commit()
    return model    

def test_favorited_by(self):
        user = create_model(User, username='user', email='user@user.net', password='password')
        user1 = create_model(User, username='user1', email='user1@user.net', password='password')
        user2 = create_model(User, username='user2', email='user2@user.net', password='password')


        file = create_model(File, name='file', description='a description', user=user)

        file.favorite(user1)
        file.favorite(user)
        file.favorite(user2)
        db.session.commit()
        print file.favorited_by

导致此查询:

SELECT "user".id AS user_id, "user".email AS user_email, "user".username AS user_username, "user".password AS user_password, "user".active AS user_active, "user".last_login_at AS user_last_login_at, "user".current_login_at AS user_current_login_at, "user".last_login_ip AS user_last_login_ip, "user".current_login_ip AS user_current_login_ip, "user".login_count AS user_login_count, "user".last_updated AS user_last_updated, "user".created_at AS user_created_at 
FROM "user", file_favorites 
WHERE :param_1 = file_favorites.file_id AND "user".id = file_favorites.user_id

最终返回user1,如果订单被切换,第一个收藏文件的用户将始终是用户返回的。

1 个答案:

答案 0 :(得分:2)

您的问题出在is_favorite_of。它没有将user合并到支票中。您需要添加另一个过滤器。

def is_favorite_of(self, user):
    query = File.query
    query = query.join(file_favorites)
    query = query.filter(file_favorites.c.file_id == self.id)
    query = query.filter(file_favorites.c.user_id == user.id)
    return query.count() > 0

或者,整个功能可以简化为:

def is_favorite_of(self, user):
    return user in self.favorited_by