由flask sqlalchemy模型中的关系字段创建的数据库字段

时间:2014-05-14 00:20:40

标签: python flask sqlalchemy

说...
国家 城市 学校 学生

如果我的数据库设置如此,并且我在学校中有一个布尔值goodOrBadStudent的字段,是否有一种简单的方法来计算每个表中有多少好学生?

NationGoodStudents = y
StateGoodStudents = x
等等......?

这是我的真实数据,但想法是一样的

class Projects(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    total = db.Column(db.Integer)
    percentDeadline = db.Column(db.Integer)
    percent = db.Column(db.Integer)
    name = db.Column(db.String(50))
    goals = db.relationship('Goals', backref='proj',
                                lazy='dynamic')
    def __repr__(self):
        return '<Project %r>' % (self.name)

class Goals(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    goal = db.Column(db.String(50))
    project_id = db.Column(db.Integer, db.ForeignKey('projects.id'))
    strategies = db.relationship('Strategies', backref='goa',
                                lazy='dynamic')

    def __repr__(self):
        return '<Goals %r>' % (self.goal)
class Strategies(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    strategy = db.Column(db.String(50))
    goal_id = db.Column(db.Integer, db.ForeignKey('goals.id'))
    tasks = db.relationship('Tasks', backref='strat',
                                lazy='dynamic')
    def __repr__(self):
        return '<Strategy %r>' % (self.strategy)

class Tasks(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    task = db.Column(db.String(50))
    note = db.Column(db.String(400))  
    complete = db.Column(db.Boolean())
    staff = db.Column(db.String(30))
    deadline = db.Column(db.Date)
    completeDate = db.Column(db.Date)
    created = db.Column(db.Date)
    strategy_id = db.Column(db.Integer, db.ForeignKey('strategies.id'))

    def __repr__(self):
        return '<Tasks %r>' % (self.task)

那么我在哪里进行计算?我希望不要在视野中,因为这很麻烦。

这是我开始做的事情来获得百分比,但可能更好地传递x y和总数

P=models.Projects.query.all()
for p in P:  
    y=0     
    x=0
    total=0
    project=models.Projects.query.filter_by(name=p.name).first() 
    G=project.goals.all()
    for g in G:
        pgoal=models.Goals.query.filter_by(goal=g.goal).first() 
        S=pgoal.strategies.all()
        for s in S:
            pstrat=models.Strategies.query.filter_by(strategy=s.strategy).first() 
            T=pstrat.tasks.all()
            for t in T:
                if t.completeDate != None and t.deadline != None:
                    deadlineDiff= (t.deadline - t.completeDate) > datetime.timedelta(days=0)
                    print deadlineDiff, ' this is the deadlineDiff variable for ',t.task
                    if deadlineDiff==True:
                        y+=1
                total+=1
                if t.complete==True:
                    x+=1
    y=float(y*1.00)
    x=float(x*1.00)
    total=float(total*1.00)
    if x == 0 or total ==0:
        p.percent=0
        db.session.commit()
    else:
        p.percent=float(x/total*100.0)
        db.session.commit()   
    if y == 0 or x ==0:
        p.percentDeadline=0
        db.session.commit()
    else:
        p.percentDeadline=float(y/x*100.0)
        db.session.commit()     

我想我会在每个级别提交x,y和总数吗?

1 个答案:

答案 0 :(得分:1)

在我看来,这种计算最好直接在SQL端执行。使用下面的sqlalchemy查询将返回tuple s (project_id, x, y, total)的列表,因为这些是在示例代码中定义的。鉴于您在数据库中拥有所有正确的索引,此查询应该非常快,您可以使用它来动态计算每个给定项目的进度,甚至不将结果存储在数据库中。

q_sum = (session.query(
            Projects.id.label("project_id"),
            func.sum(case([(Tasks.complete == True, 1)], else_=0)).label("x"),
            func.sum(case([(and_(
                Tasks.deadline != None,
                Tasks.completeDate != None,
                Tasks.deadline > Tasks.completeDate), 1)],
                else_=0)).label("y"),
            func.count(Tasks.id).label("total"),
            )
        .join(Goals, Projects.goals)
        .join(Strategies, Goals.strategies)
        .join(Tasks, Strategies.tasks)
        .group_by(Projects.id)
        )

# (project_id, x, y, total)
for p in q_sum:
    print(p)

如果您只需要针对特定​​项目获取此内容,只需将.filter(Project.id == my_project_id)添加到查询中即可。