如何使用pydantic序列化模型的所有相关模型

2024-06-01 01:09:44 发布

您现在位置:Python中文网/ 问答频道 /正文

设置(龟形模型):

class Hand(BaseModel):
    id: int
    fingers: fields.ReverseRelation["Finger"]


class Finger(BaseModel):
    id: int
    hand: fields.ForeignKeyField(model_name="models.User", related_name="fingers", null=True)

假设我们有一个手的id,我们希望将其所有相关的手指返回给用户。我应该如何为它创建pydantic模型,以及如何查询所有提到的手指

到目前为止我所尝试的(没有运气):

#1

    Fingers_dto = pydantic_queryset_creator(Finger)
    hand = await Hand.get(pk=id).prefetch_related("fingers")
    return await Fingers_dto.from_queryset(hand.fingers)

#2

    Fingers_dto = Finger.create_query_set()
    hand = await Hand.filter(pk=id)
    await hand.fetch_related("fingers")
    return await Fingers_dto.from_queryset(hand.fingers)

Tags: 模型idfieldsawaitclassbasemodelintqueryset
1条回答
网友
1楼 · 发布于 2024-06-01 01:09:44

为了实现这一目标,我必须做到以下几点:

Fingers_dto = pydantic_queryset_creator(Finger)
hand = await Hand.get(pk=id)
return await Fingers_dto.from_queryset(hand.fingers.all())

相关问题 更多 >