【发布时间】:2020-02-24 06:07:14
【问题描述】:
我很难从我的员工数据库表中返回键和值计数,每个客户都给员工打分。我想返回每个工人的评级。我的数据库模型,端点如下:
@classmethod
def distinct_rating_count(cls, _workerId):
return {'rating_count': [c[0] for c in
db.session.query
(func.count(distinct(RatingModel.rating)))
.filter_by(workerId=_workerId)
.group_by(RatingModel.rating)]}
类 RatingModel(db.Model):
__tablename__ = 'rating'
id = db.Column(db.Integer(), primary_key=True)
rating = db.Column(db.Integer(), nullable=False)
rateDate = db.Column(db.DateTime, default=datetime.datetime.utcnow)
comments = db.Column(db.String(512), nullable=True)
userId = db.Column(db.Integer(), db.ForeignKey('users.id'))
user = db.relationship('UserModel')
workerId = db.Column(db.Integer(), db.ForeignKey('workers.id'))
worker = db.relationship('WorkerModel')
def __init__(self, userId, workerId, rating, comments):
self.userId = userId
self.workerId = workerId
self.rating = rating
self.comments = comments
类 DistinctRatingCount(Resource):
def get(self, workerId):
ratingcount = RatingModel.distinct_rating_count(workerId)
if ratingcount:
return ratingcount
else:
return {'message': 'There is no rating yet'}
classmethod distinct_rating_count 返回:
{ “评分计数”:[ 1、 1、 1 ] }
但是,我想要字典之类的东西,如果某些工人没有评级值,例如在下面的示例中,没有一个评级为“1”和“4”的工人,那么它应该被标记为 0 次:
{"1":0,"2":3,"3":5,"4":0,"5":2}
我已经尝试了很多搜索 stackoverflow 并用谷歌搜索它,我无法得到正确的线索。提前致谢。
/////////////////////////////////////// /////////////////////// 最后根据@Shivendra Pratap Kushwaha 技术稍加修改,我整理如下:
@classmethod
def distinct_rating_count(cls, _workerId):
rating = dict(cls.query.with_entities
(RatingModel.rating, func.count(
RatingModel.rating))
.group_by(RatingModel.rating)
.filter_by(workerId=_workerId))
----------{ “1”:2, “4”:1, “5”:2 }
【问题讨论】:
标签: python api flask flask-sqlalchemy