# How to select from select distinct ?

**URL:** <https://forum.djangoproject.com/t/how-to-select-from-select-distinct/15616>\
**Category:** Forms & APIs\
**Created:** [August 26, 2022, 9:09am UTC](https://forum.djangoproject.com/t/how-to-select-from-select-distinct/15616 "2022-08-26T09:09:36Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![vilkh3m](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/vilkh3m/32/9845_2.png) [@vilkh3m](https://forum.djangoproject.com/u/vilkh3m)\
**Post date:** [August 26, 2022, 9:09am UTC](https://forum.djangoproject.com/t/how-to-select-from-select-distinct/15616/1 "2022-08-26T09:09:36Z")

</div>

Hi,

I’m using django-tables2 with django-filter  
in the table, I always want the results grouped by build\_type\_id  
in filter.py got class ResultsFilter(FilterSet) and there i add to qs distinct part:

```auto
@property
    def qs(self):
        parent = super().qs
        return parent.distinct('build_type_id').order_by('build_type_id', '-id')

```

and all works fine filtering working ok, problem is with ordering  
I would like to be able to sort the results from distinct select in django-table2

i go postgresql query which works

```auto
select * from (
    SELECT DISTINCT
    ON ("builds_results"."build_type_id") "builds_results"."id",
                                          "builds_results"."build_type_id",
                                          "builds_results"."created_at",
                                          "builds_results"."status"
   FROM "builds_results"
   ORDER BY "builds_results"."build_type_id" ASC, "builds_results"."id" DESC
) t
order by "t"."created_at" ASC

```

how can i get this effect in django ?

---

<div class="post-metadata">

**Author:** ![vilkh3m](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/vilkh3m/32/9845_2.png) [@vilkh3m](https://forum.djangoproject.com/u/vilkh3m)\
**Post date:** [August 29, 2022, 5:37am UTC](https://forum.djangoproject.com/t/how-to-select-from-select-distinct/15616/2 "2022-08-29T05:37:40Z")

</div>

no one had a problem similar to mine?

---

<div class="post-metadata">

**Author:** ![vilkh3m](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/vilkh3m/32/9845_2.png) [@vilkh3m](https://forum.djangoproject.com/u/vilkh3m)\
**Post date:** [September 25, 2022, 4:20pm UTC](https://forum.djangoproject.com/t/how-to-select-from-select-distinct/15616/3 "2022-09-25T16:20:41Z")

</div>

if any one need sort distinct result

```auto
def qs(self):
    parent = super().qs
    q = parent.distinct('product__release', 'name').order_by('product__release', 'name', '-id')
    return sorted(q, key=operator.attrgetter('created_at'), reverse=True)

```
