tortoise / tortoise/tortoise-orm

"distinct on" feature

Open
#135 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

I need to retrieve the latest record in the DB for certain device and to do that I need to use SQL DISTINCT feature.
Now I saw that the Tortoise package have distinct method but I didn't find a usage in the example (that worked for me), the query just froze

In raw SQL the query working fine and I'm trying to understand If im doing anything wrong with the ORM (I hope this is the case)

The expected result is that I will retrieve the latest users from the users table (where account ID is 1) from the users table

SQL query:

select distinct on (user_id) u.* from users u where account_id = 1 order by user_id, created_at desc;

The ORM usage:

result = await Users.filter(account_id=1).order_by('created_at').distinct().values('user_id').all()

Am I doing something wrong here ??

Thanks for the help ! :)

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

Start by comparing the ORM usage in the issue with the PostgreSQL query using DISTINCT ON, focusing on how distinct(), order_by(), and values() are expected to interact. Reproduce the query against PostgreSQL and determine the intended ORM behavior; done means the requested latest-per-user result is supported or the limitation is clearly documented.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.