Query One to Many Relationship SQLAlchemy

后端 未结 1 501
悲哀的现实
悲哀的现实 2021-01-03 11:41

I am trying to query the users based upon their skills from these tables.

class User(UserMixin, db.Model):
    __tablename__ = \'users\'

    id = db.Column(         


        
相关标签:
1条回答
  • 2021-01-03 12:44

    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()
    
    0 讨论(0)
提交回复
热议问题