简体   繁体   English

查询一对多关系 SQLAlchemy

[英]Query One to Many Relationship SQLAlchemy

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?我在哪里严重失踪?

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.这意味着users_by_skillskill参数是一个字符串。 Then, you try to use skill.skill , which essentially is like doing 'nunchuk'.skill .然后,您尝试使用skill.skill ,这本质上就像在做'nunchuk'.skill Python does not have a skill attribute on the string class, hence the error. Python 在字符串类上没有skill属性,因此出现错误。

The filter function actually takes a Criteria object. filter函数实际上接受一个Criteria对象。 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'".换句话说,您没有向它传递像"filter"这样的值,而是向它传递一个标准,该标准表示“技能表上的技能列必须等于 '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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM