根据sqlachemy中其他表的名称从Closure表进行查询

时间:2021-04-25 11:45:42

标签: python sqlalchemy

我的数据库中有三个表。

Task 表是

<头>
idTask 任务 descendant_id
1 1+2+3+4 4
2 6+7+8+9 4

Topic 表是

<头>
id_c name_category
1 数学
2 代数
3 进步
4 数字序列

ClosureTableCategory

<头>
祖先 后代 深度
1 1 0
1 2 1
1 3 2
1 4 3
2 2 0
2 3 1
2 4 2
3 3 0
3 4 1
4 4 0

在 SQL Alchemy 中,结构是:

db = SQLAlchemy(app)
migrate = Migrate(app, db)

class Task(db.Model):
    __tablename__ = 'task'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    task = db.Column(db.Text)
    topics = db.relationship('Topic', backref='task')
    topics_id = db.Column(db.Integer, db.ForeignKey('topic.id'))


class ClosureTableCategory(db.Model):
    __tablename__ = 'ClosureTableCategory'
    id = db.Column(db.Integer, primary_key=True)
    ancestor_id = db.Column(db.Integer, db.ForeignKey('topic.id'))
    descendant_id = db.Column(db.Integer, db.ForeignKey('topic.id'))
    depth = db.Column(db.Integer, nullable=False)

# ancestor = db.relationship('Topic', foreign_keys=[ancestor_id])
# descendant = db.relationship('Topic', foreign_keys=[descendant_id])


class Topic(db.Model):
    __tablename__ = 'topic'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(140))
    descendant = db.relationship(
        'Topic',
        backref='ancestors',
        secondary='ClosureTableCategory',
        primaryjoin=id == ClosureTableCategory.ancestor_id,
        secondaryjoin=id == ClosureTableCategory.descendant_id
    )

我需要按名称从任务表中获取查询。我的代码是:

top   = Topic.query.filter(Topic.name == "Algebra").first()
top_2 = ClosureTableCategory.query.filter(db.or_(ClosureTableCategory.descendant_id == top.id,ClosureTableCategory.ancestor_id==top.id)).all()

top_3 =[]
for topi in top_2:
    top_3.append(topi.ancestor_id)
    top_3.append(topi.descendant_id)

top_4 = Task.query.filter(Task.topics_id.in_(top_3)).all()
for topi in top_4:
    print(str(topi.task))

它有效,但在我看来代码非常庞大和糟糕。如何让它更小更高效?

0 个答案:

没有答案
相关问题