【问题标题】:SqlAlchemy Query to Select Rows Without ChildrenSqlAlchemy 查询以选择没有子项的行
【发布时间】:2020-12-25 01:45:59
【问题描述】:

我有一个 Tag 表,它可以有一个父级 Tag 的同一类。

我希望查询返回所有没有任何子级的 Tag 实例。

这是 SqlAlchemy 类的代码:

class Tag(db.Model):
    __tablename__ = 'tags'

    id = db.Column(db.String(32), primary_key=True)
    name = db.Column(db.String(45),nullable=False)
    subject_id = db.Column(db.Integer, db.ForeignKey('subjects.id'), nullable=False)
    parent_tag_id = db.Column(db.Integer, db.ForeignKey('tags.id'), nullable=True)

    subject = db.relationship('Subject', backref=db.backref('tags', lazy='dynamic'))
    parent_tag = db.relationship('Tag',
                                 remote_side=[id],
                                 backref=db.backref('children', lazy='dynamic'))

    def __init__(self, name, subject_id, parent_tag_id=None):
        self.id = uuid.uuid4().hex
        self.name = name
        self.subject_id = subject_id
        self.parent_tag_id = parent_tag_id

这是我对查询的最佳尝试:

def get_all_subject_tags_ordered():
    _child_tag = aliased(Tag)
    return db.session.query(Tag)\
        .join(_child_tag, Tag.children)\
        .filter(func.count(Tag.children) == 0)\
        .filter(Tag.subject_id.isnot(None))\
        .order_by(Tag.name)\
        .all()

这给了我错误:

sqlalchemy.exc.ProgrammingError: (pymysql.err.ProgrammingError) (1111, u'无效使用组函数') [SQL: u'SELECT tags.id AS tags_id, tags.name AS tags_name, tags.subject_id AS tags_subject_id, tags.parent_tag_id AS tags_parent_tag_id \nFROM tags INNER JOIN tags AS tags_1 ON tags.id = tags_1.parent_tag_id \nWHERE count(tags.id = tags.parent_tag_id) = % (count_1)s AND tags.subject_id 不为空 ORDER BY tags.name'] [参数:{u'count_1': 0}]

非常感谢您的帮助。

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    一般来说:db.session.query(Parent).filter(Parent.children==None) 会找到所有 Parents,但没有 children

    那就试试吧:

    return db.session.query(Tag)\
        .filter(Tag.children == None, Tag.subject_id != None)\
        .order_by(Tag.name)\
        .all()
    

    【讨论】:

    • 我也向您推荐这个alternate solution,在这种情况下您可以尝试:.filter(~Tag.children.any())
    • 两种解决方案都运行良好。非常感谢:)
    猜你喜欢
    • 2021-05-06
    • 2017-09-21
    • 1970-01-01
    • 2018-01-05
    • 2014-10-15
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多