Skip to content

from_tortoise_orm generated redundant queries #2115

@seejah

Description

@seejah

The code is as follows:

query = User.get_or_none(id=id).prefetch_related('roles')
result = await User_Pydantic.from_tortoise_orm(await query)

** User and Role is M2M relationship.

From the logs, You can see that it executed 3 queries, with the third one being obviously redundant:

# 1st
SELECT `id`,`name`,`phone` FROM `user` WHERE `id`=%s ASC LIMIT %s : [1, 2]

# 2nd
SELECT `sq0`.`_backward_relation_key` `_backward_relation_key`,`role`.`name` `name`,`role`.`code` `code`,`role`.`id` `id`
FROM `role` JOIN (SELECT `user_id` `_backward_relation_key`,`role_id` `_forward_relation_key` FROM `role_user`
WHERE `user_id` IN (%s)) `sq0` ON `sq0`.`_forward_relation_key`=`role`.`id` : [1]

# 3rd
SELECT `sq0`.`_backward_relation_key` `_backward_relation_key`,`role`.`name` `name`,`role`.`code` `code`,`role`.`id` `id`
FROM `role` JOIN (SELECT `user_id` `_backward_relation_key`,`role_id` `_forward_relation_key` FROM `role_user`
WHERE `user_id` IN (%s)) `sq0` ON `sq0`.`_forward_relation_key`=`role`.`id` : [1]

If I return the queryset directly instead of executing from_tortoise_orm, the SQL will be executed twice (properly).
Did I write something incorrectly there?

Of course, the above issue is not a bug, just an efficiency problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions