Python 在flask sqlalchemy(flask restful API)中选择不同的键和值计数
我很难从我的工人数据库表中返回键和值计数,每个客户都给工人打分。我想返回每个工人的评分。我的DB型号,终点如下:Python 在flask sqlalchemy(flask restful API)中选择不同的键和值计数,python,api,flask,flask-sqlalchemy,Python,Api,Flask,Flask Sqlalchemy,我很难从我的工人数据库表中返回键和值计数,每个客户都给工人打分。我想返回每个工人的评分。我的DB型号,终点如下: @classmethod def distinct_rating_count(cls, _workerId): return {'rating_count': [c[0] for c in db.session.query (func.count(distinc
@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)]}
等级模型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
类distinctionCountResource:
def get(self, workerId):
ratingcount = RatingModel.distinct_rating_count(workerId)
if ratingcount:
return ratingcount
else:
return {'message': 'There is no rating yet'}
classmethod distinct\u rating\u count返回:
{
评级单位计数:[
1.
1.
1.
]
}
然而,我想要一些东西,比如字典,如果一些工人没有评级值,比如在下面的例子中,没有一个工人的评级为1和4,那么它应该标记为0倍:
{1:0,2:3,3:5,4:0,5:2}
我已经尝试了很多来搜索stackoverflow并用谷歌搜索了它,但我找不到正确的线索。提前谢谢
////////////////////////////////////////////////////////////////////////
最后,根据@Shivendra Pratap Kushwaha技术,稍加修改,我将其分类如下:
@类方法
def distinct_rating_COUNTCL,_workerId:
评级=dictcls.query.with_实体
评级模型.评级,功能计数
评级模型
.group_byRatingModel.rating
.filter\u byworkerId=\u workerId
-----{
1: 2,
4: 1,
5: 2
}这可能会给你一个如何做到这一点的例子。 在本例中,我以简单学生模型为例: 学生模型: 1.id 2.主题 3.学校id 现在,我想计算student.id和具有特定school_id的所有行中相应的科目数 我需要一些像CountStudDic={1:0,2:3,3:5,4:0,5:2}这样的词汇,就像你的一样 因此,以下是如何实现这一目标:
CountStudDic = dict(Student.query.with_entities(Student.id,func.count(Student.subject)).group_by(Student.subject).filter_by(school_id=str(current_user.id)).all())
基本思想是将实体和转换为字典。非常感谢,您的技术对我来说非常有效,几乎没有修改。你太棒了!