Reputation: 747
Setup (tortoise-orm models):
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)
Let's say that we have an id of a hand, and we want to return its all related fingers to the user. How should I create pydantic model for it, and how should I query all fingers mentioned?
What I've tried so far (with no luck):
#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)
Upvotes: 2
Views: 1290
Reputation: 747
To achieve this I had to do following:
Fingers_dto = pydantic_queryset_creator(Finger)
hand = await Hand.get(pk=id)
return await Fingers_dto.from_queryset(hand.fingers.all())
Upvotes: 1