python FLASK SQLAlchemy查询,过滤并给予多个返回

j0pj023g  于 2022-10-30  发布在  Python
关注(0)|答案(1)|浏览(187)

我尝试用flak-sqlalchemy创建一个API,它接受employee_id数字并返回他们的所有信息。一些雇员在两个部门,所以我想让它返回雇员可能属于的所有部门的json。代码运行,但当我输入雇员ID时,它给我一个空列表。

@app.route('/getrate/<int:employee_id>', methods=['GET', 'POST'])
def getrate(employee_id):
    ratings=employee_ratings.filter_by(employee_id="employee_id").all()
    allRatings=[]
    for rating in ratings:
        newResponse={
            "id":rate.id,
            "employee_id":rate.employee_id,
            "name":rate.name,
            "department":str(rate.department),
            "phone":rate.phone,
            "title":str(rate.title),
            "score":rate.score,
            "rank":str(rate.rank)  
        }

        # print(type(newResponse))
        allRatings.append(newResponse)

    all = {
        "all":allRatings
    }

    print(type(all))

    return all
flvtvl50

flvtvl501#

您为SQLAlchemy提供了一个字符串,而不是真实的的employee_id。因此,您必须将评级更改为:

ratings = credit_scores.query.filter_by(employee_id=employee_id).all()

我看到的第二个问题是,你引用了一个没有赋值的变量,它是rate。你必须把rate改为rating

for rating in ratings:
    newResponse = {
        "id":rating.id,
        "employee_id":rating.employee_id,
        "name":rating.name,
        "department":str(rating.department),
        "phone":rating.phone,
        "title":str(rating.title),
        "score":rating.score,
        "rank":str(rating.rank)  
    }

    # print(type(newResponse))
    allRatings.append(newResponse)

事实上,我不确定,如果你的DBMS已经将部门存储为数据结构化列表。如果是这样的话,那么将str(rating.department)更改为list(rating.department),它在JSON格式下仍然有效。

相关问题