问题
I am trying to query the users based upon their skills from these tables.
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)
skills = db.relationship('Skill', backref='author', lazy='dynamic')
class Skill(db.Model):
__tablename__ = 'skills'
id = db.Column(db.Integer, primary_key=True)
skill = db.Column(db.String(64), index=True)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
i tried this in User table and got this error.
@classmethod
def users_by_skill(cls, skill):
return User.query.join(Skill).filter(skill.skill).all()
AttributeError: 'str' object has no attribute 'skill'
Where i am missing badly?
回答1:
You define the following class method:
@classmethod
def users_by_skill(cls, skill):
return User.query.join(Skill).filter(skill.skill).all()
You are probably expecting to use this function like so:
users = Users.users_by_skill('nunchuk')
That means the skill
argument in users_by_skill
is a string. Then, you try to use skill.skill
, which essentially is like doing 'nunchuk'.skill
. Python does not have a skill
attribute on the string class, hence the error.
The filter function actually takes a Criteria
object. In other words, you don't pass it a value like "filter"
, you instead pass it a criterion that represents the notion of "the skill column on the Skill table must equal 'nunchuk'". You can do this using syntax like the following:
@classmethod
def users_by_skill(cls, skill_name):
return User.query.join(Skill).filter(Skill.skill == skill_name).all()
来源:https://stackoverflow.com/questions/24454910/query-one-to-many-relationship-sqlalchemy