Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
73 views
in Technique[技术] by (71.8m points)

Marshmallow deserialization [(obj, "str"), (obj, "str"), (obj, "str"), ...]

I'm working with an existing mssql database, where I'm not able to make any changes. Trying to make an API using Flask and Marshmallow. I have some issues deserializing the following query returning all people working on a project.

query = (
        sa.session.query(Employee, sa.func.sum(JobEntry.number_registered).label("total"))
        .join(JobEntry, Employee.employee_hashkey==JobEntry.employee_hashkey)
        .filter(JobEntry.project_number==f'{project_number}')
        .group_by(Employee)
    ).limit(3).all()

The query returns

print(query)
[(<Employee 188ED6A858997A48FDA53A404779A16F>, 229.0), (<Employee 1D40AB9C2A973C2BD33B1EF6108D2A70>, 2.0), (<Employee 38584E42E883131DC35151E4922A8094>, 176.75)]

The Employee contains the name, id, etc. How would I create a marshmallow schema returning, the following example.

[
    {"name": "somename a", "total" 229.0, "id": 11},
    {"name": "somename b", "total" 2.0, "id": 22},
    {"name": "somename c", "total" 176.75, "id": 33}
]

Being a noob, I have experimented a bit... The following code returns almost what I want. But I get "Employee." in my keys ...

class ProjectUsersSchema(Schema):
class Meta:
    model = Employee

    fields = (
        "Employee.name",
        "Employee.id"
        "total"
    )

# returns "[{"Employee.name": "somename a", "total" 229.0, "Employee.id": 11}, ..."
question from:https://stackoverflow.com/questions/65934710/marshmallow-deserialization-obj-str-obj-str-obj-str

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Made a temporary f#ckly fix using nested schemas by including .split(".")[-1] into my snake_case to PascalCase schema

def pascalcase(s):
    part_lst = s.split(".")[-1].split("_") # todo fix split(".")[-1] 
    if len(s) <= 2:
        return "".join(i.upper() for i in part_lst)
    else:
        return "".join(i.title() for i in part_lst)


class PascalCaseSchema(ma.SQLAlchemyAutoSchema):

def on_bind_field(self, field_name, field_obj):
    field_obj.data_key = pascalcase(field_obj.data_key or field_name)`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...