Django query select distinct by field pairs

前端 未结 2 1811
生来不讨喜
生来不讨喜 2021-02-09 03:15

I have the field \'submission\' which has a user and a problem. How can I get an SQL search result which will give a list of only one result per user-problem pair?

Model

2条回答
  •  情书的邮戳
    2021-02-09 04:17

    Try this:

    distinct_users_problems = Submission.objects.all().values("user", "problem").distinct()
    

    It will give you a list of dicts like this one:

    [{'problem': 1, 'user': 1}, {'problem': 2, 'user': 1}, {'problem': 3, 'user': 1}]
    

    containing all the distinct pairs.

    It actually results in your usual SELECT DISTINCT SQL query.

提交回复
热议问题