SQLAlchemy generating query in loop with contains
我正在Flask中构建一个涉及到一些SQLAlchemy的Web应用程序。我有一个函数"get_team()",这让我很疯狂。
1 2 3 4 | def get_team(playerlist) cond = and_(*[Team.users.contains(p) for p in playerlist ]) q = Team.query.filter(cond) ... |
我不断地得到错误:"attributeError:'unicode'对象没有属性'u sa_instance_state'"。模型如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class Team(db.Model): __tablename__ = 'teams' id = db.Column(db.Integer, primary_key=True) users = association_proxy("user_associations","user", creator=lambda u: Teaming(user=u)) def __repr__(self): s ="" for u in self.users: s = s + u.username +"," return"Team {tid}: {users_string}".format(tid = self.id, users_string=s) class Teaming(db.Model): __tablename__ = 'teaming' team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) user = db.relationship("User", backref="team_associations") team = db.relationship("Team", backref="user_associations") def __repr__(self): return"".format(uid = self.user_id, tid = self.team_id) class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(64), unique=True, index=True) username = db.Column(db.String(64), unique=True, index=True) password_hash = db.Column(db.String(128)) confirmed = db.Column(db.Boolean, default=False) teams = association_proxy("team_associations","team", creator = lambda t: Teaming(team=t)) |
任何指示都将非常感谢!
最可能的原因是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def get_team_of_players(playerlist): cond = and_(*[Team.users.contains(p) for p in playerlist]) q = Team.query.filter(cond) return q p1, p2 = db.session.query(User).get(1), db.session.query(User).get(2) q = get_team_of_players([p1, p2]).all() def get_team_of_usernames(usernames): cond = and_(*[Team.users.any(User.username == p) for p in usernames]) q = Team.query.filter(cond) return q p1, p2 = 'user1', 'user2' q = get_team_of_usernames([p1, p2]).all() |