Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-viewsdjango-orm

duplicate record when combine `distinct` and `order_by`


when I get API with ordering by product__company__name, the API responds the result as me as expected, but with 2 records duplicated. I read the Note in this docs https://docs.djangoproject.com/en/3.2/ref/models/querysets/#distinct that If you order by fields from a related model, those fields will be added to the selected columns and they may make otherwise duplicate rows appear to be distinct. Since the extra columns don’t appear in the returned results (they are only there to support ordering), it sometimes looks like non-distinct results are being returned. So how can I resolve this problem? I just want to order a product based on the company name. Thank you so much.

    def get_queryset(self):
            qs = MyModel.objects.filter(
                   <logic_code>
            )
            return qs.distinct().order_by("product__company__name")


Solution

  • While finding the solution with ORM, I convert it to the list and resolved this problem.