Query One to Many Relationship SQLAlchemy

。_饼干妹妹 提交于 2020-11-27 04:05:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!