Hacktoberfest 2026:维护者为十月标记出来的 issue,仍然开放、适合新手。 浏览 Hacktoberfest issue

Add exists filter syntax

未关闭
#2,002 2 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 2 天内回复

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
42/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
冷清
技术栈
python, sql
领域
databases

调研方向

从相关 issue #385 开始,将提议的过滤语法与此 issue 中的 EXISTS 和 JOIN SQL 示例进行比较。明确 __exists 应该放在哪里,以及它的语义应该是什么;完成的标准是达成一种共识语法,能够生成基于存在性的过滤,而无需使用 distinct()。

由索引模型根据 Issue 内容生成。

描述

Is your feature request related to a problem? Please describe.

When querying for the existence of a one-to-many related model with certain values it one of its fields, the .distinct() method is required to prevent duplicates. This is not the most efficient query.

Contrived example: I have to do this to find all phone numbers of users that work at the north pole without duplicates:

PhoneNumber.filter(user__company__location='North Pole').distinct()

According to ChatGPT,

SELECT m.*
FROM model m
WHERE EXISTS (
    SELECT 1
    FROM user u
    JOIN company c ON u.company_id = c.id
    WHERE u.id = m.user_id
      AND c.location = 'North Pole'
);

is preferable over

SELECT DISTINCT m.*
FROM model m
LEFT OUTER JOIN user u ON m.user_id = u.id
LEFT OUTER JOIN company c ON u.company_id = c.id
WHERE c.location = 'North Pole';

Why this is better (copied from ChatGPT):

  • EXISTS checks for existence rather than joining, so no duplicates.
  • Often more efficient, since the DB can stop searching after the first match.
  • Cleaner semantics: “Does this related row exist?” rather than “Give me all the related rows, then deduplicate.”

Describe the solution you'd like

PhoneNumber.filter(user__company__exists__location='North Pole')

Describe alternatives you've considered

Could be variations on the placement of __exists in the query. I realize the exact semantics could be a bit unclear.

Additional context

Related #385

主要语言
Python
星标
5.6k
派生
523
平均合并
2 天 18 小时
30 天内合并 PR
12

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

tortoise/tortoise-orm 的其他 Issue

查看 tortoise/tortoise-orm 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。