【问题标题】:select distinct key and value counts in flask sqlalchemy ( flask restful API)在flask sqlalchemy(flask restful API)中选择不同的键和值计数
【发布时间】: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


    【解决方案1】:

    这可能会给你一个例子来说明它是如何做到的。 在这种情况下,我以简单的学生模型为例:

    学生模型:

    1.)id

    2.)主题

    3.)school_id

    现在我想从所有具有特定 school_id 的行中计算 student.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())
    

    基本思想是同时获取实体并转换为字典。

    【讨论】:

    • 非常感谢,您的技术对我有用,几乎没有修改。你太棒了!
    猜你喜欢
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2019-05-31
    • 1970-01-01
    相关资源
    最近更新 更多