我在Flask中构建一个涉及一些SQLAlchemy的Web应用程序。我有一个功能" get_team()"这让我疯狂。
def get_team(playerlist) cond = and_(*[Team.users.contains(p) for p in playerlist ]) q = Team.query.filter(cond) ...
我一直收到错误:"属性错误:' unicode'对象没有属性' _sa_instance_state'"。这是模型的样子:
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))
任何方向都会非常感谢!
答案 0 :(得分:1)
最可能的原因是playerlist
不是User
个实例的列表,而是一些字符串(可能是名称)。 contains
仅适用于模型实例。如果您想使用其他属性,请使用any
。
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()