如何根据每个项目的每个驱动程序的driver.factor次数project_driver.value对每个项目的列表进行排序或返回?所以应该有一个额外的计算/动态字段/列"评级"在项目中。
例如:
project1.rating =(10.0 * 0.7)+(40.0 * 0.2)+(20.0 * 0.1)
谢谢
模型:
class ProjectDriver(db.Model):
project_id = db.Column(db.Integer, db.ForeignKey('project.id'),
primary_key=True)
driver_id = db.Column(db.Integer, db.ForeignKey('driver.id'),
primary_key=True)
value = db.Column(db.Float)
driver = db.relationship('Driver', backref=db.backref('project_drivers'))
def __init__(self, value, driver):
self.value = value
self.driver = driver
def __repr__(self):
return '<ProjectDriver %r, %r>' % (self.project_id, self.driver_id)
class Project(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120))
project_drivers = db.relationship('ProjectDriver',
backref=db.backref('projects'))
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Project %r>' % self.name
class Driver(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120))
factor = db.Column(db.Float)
def __init__(self, name, factor):
self.name = name
self.factor = factor
def __repr__(self):
return '<Driver %r>' % self.name
的观点:
@app.route('/projects')
def list_view():
projects = Project.query.all()
return render_template('list_view.html', projects=projects)
源码:
sqlite> select * from project;
id name
---------- ----------
1 Project1
2 Project2
3 Project3
sqlite> select * from driver;
id name factor
---------- ---------- ----------
1 Driver1 0.7
2 Driver2 0.2
3 Driver3 0.1
sqlite> select * from project_driver;
project_id driver_id value
---------- ---------- ----------
1 1 10.0
1 2 40.0
1 3 20.0
2 1 20.0
2 2 10.0
2 3 30.0
3 1 50.0
3 2 20.0
3 3 10.0
答案 0 :(得分:3)
看看hybrid properties。在您的项目驱动程序类中,例如:
@hybrid_property
def rating(self):
return self.factor * self.driver.factor
然后在项目中进行加法计算