How to use DTO to "return relations" #710
-
Hello. I'm using the Tortoise plugin and I want to know how can I return the values of a relation in the controller. If i have a relation between two models, for example: class User(Model):
id = fields.IntField(pk=True)
name = fields.CharField(max_length=255)
class Photo(Model):
id = fields.IntField(pk=True)
number = fields.CharField(max_length=255)
status = fields.CharField(max_length=255)
user = fields.ForeignKeyField('models.User', related_name='users')
UserDTO = dto_factory("UserDTO", User) In the controller i'm doing: @get()
async def list_users() -> list[UserDTO]:
users = await User.all()
return cast("list[UserDTO]", users ) But this returns only |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
It doesn't show up there because when DTO factories are created Tortoise is not aware of relations. Internally the plugin uses Please refer to Tortoise docs |
Beta Was this translation helpful? Give feedback.
It doesn't show up there because when DTO factories are created Tortoise is not aware of relations. Internally the plugin uses
tortoise.contrib.pydantic.pydantic_model_creator
which can work with relations if models have been initialized before its invocation.Please refer to Tortoise docs