Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

python - How to 'select distinct on' as a subquery using django filters

I'm creating a search function for my django project and was wondering how I can group rows while ordering them by the amount of points the players have scored.

I want to be able to group them and when it finds values with the same name, it just takes the first value

The solution I found on postgresql

select * from 
(select distinct on (name) * from database_manager_player) t
order by pts desc;

database values:

name team pts
andrew A 20
andrew B 24
andrew C 12
jones B 8
jones C 6

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To select distinct on, you have to use a subquery

 ids = qs.distinct("name").order_by().values_list("pk", flat=True)
 qs = qs.filter(pk__in=ids)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...