i have trouble how to return key, and value counts from my DB table of workers, where each customer has given rating to workers. I want to return the rating of each worker. My DB models, end points are as below:
@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)]}
class 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
class 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 returns:
{ "rating_count": [ 1, 1, 1 ] }
However, I want some thing like dictionary, if there is no rating value for some workers, like in below example no one rated worker with rating of "1" and "4" then it should be labelled 0 times:
{"1":0,"2":3,"3":5,"4":0,"5":2}
I have tried a lot to search of stackoverflow and googled it , I could not get right clue. thanks in advance.
//////////////////////////////////////////////////////////////////////// finally according to @Shivendra Pratap Kushwaha technique with little modification, i sorted it out like below:
@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 }