tortoise/tortoise-orm

Can anyone tell me how the distinct() function is going to work?

KrisShin opened this issue · 2 comments

I just want to get the effect of this sql

select distinct some_column from table name where any_column=any_condition;

and I search distinct from document, It say like that

Make QuerySet distinct.

Only makes sense in combination with a .values() or .values_list() as it precedes all the fetched fields with a distinct.

no parameter ? OK
So I try to write this code.

await Model.filter(any_column=any_condition).values_list("some_column", flat=True).distinct()

and a bug like this was reported, distinct is a bool , can not call.
so I modify it

await Model.filter(any_column=any_condition).distinct().values_list("some_column", flat=True)

another bug was reported.

tortoise.exceptions.OperationalError: for SELECT DISTINCT, ORDER BY expressions must appear in select list

but distinct with no parameter, I can not specify a field.
And I search in example of document, You suggest combination with .values() and .values_list(), But I haven't found an example that uses either of these methods.
so I just wrote the raw sql to get the result. It's so ridiculous
I'm too confuse to use this function, can anyone help me?

Hi!

Have you tried

await Model.filter(any_column=any_condition).distinct().values_list("some_column", flat=True).order_by("some_column")

?

Have you specified Meta.ordering for your model? If this is the case then this default ordering will be used when building the query which will results in this error. To avoid this you can override the default ordering by like @abondar mentioned in his answer.