python - Query One to Many Relationship SQLAlchemy -
i trying query users based upon skills 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 in user table , got 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 missing badly?
you define following class method:
@classmethod def users_by_skill(cls, skill): return user.query.join(skill).filter(skill.skill).all()
you expecting use function so:
users = users.users_by_skill('nunchuk')
that means skill
argument in users_by_skill
string. then, try use skill.skill
, doing 'nunchuk'.skill
. python not have skill
attribute on string class, hence error.
the filter
function takes criteria
object. in other words, don't pass value "filter"
, instead pass criterion represents notion of "the skill column on skill table must equal 'nunchuk'". can using syntax following:
@classmethod def users_by_skill(cls, skill_name): return user.query.join(skill).filter(skill.skill == skill_name).all()
Comments
Post a Comment