tortoise / tortoise/tortoise-orm

How to handle the same table self-join subquery

Open
#1,548 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.6k
Forks
516
Avg merge
2d 21h
Merged PRs (30d)
9

Description

I have a model as shown below:

class SysMenu(Model):
    id = fields.IntField(pk=True)
    pid = fields.IntField()
    name = fields.CharField(max_length=200)
    url = fields.CharField(max_length=200, null=True)
    permissions = fields.CharField(max_length=500, null=True)
    menu_type = fields.SmallIntField()
    icon = fields.CharField(max_length=50, null=True)
    sort = fields.IntField()

Question:
I want to implement the following sql query. I currently use raw sql to solve, but do not know how to use orm to solve?

select t1.*, (select name from sys_menu t2 where t2.id=t1.pid) as parentName from sys_menu t1 where t1.id = #{menu_id}

Does anyone know?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue provides only the SysMenu model and target SQL; no repository file, test, or entry point is named. Start by checking Tortoise ORM's documented query expressions, annotations, and self-reference support. Done would be a documented ORM approach for the parentName result, or a clear statement that raw SQL is required.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, sql
Domain
databases
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.