本文介绍了查询一对多关系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'))

我在 User 表中尝试了此操作,并收到此错误.

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'

我在哪里很想念?

推荐答案

您定义以下类方法:

@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')

这意味着 users_by_skill 中的 skill 参数是一个字符串.然后,您尝试使用 skill.skill ,本质上就像在做'nunchuk'.skill 一样.Python在字符串类上没有 skill 属性,因此会出现错误.

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.

filter 函数实际上需要一个 Criteria 对象.换句话说,您没有向其传递像"filter" 这样的值,而是向其传递了一个表示技能表上的技能列必须等于'nunchuk'"这一概念的标准.您可以使用如下语法来做到这一点:

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()

这篇关于查询一对多关系SQLAlchemy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-05 03:41