Opened 4 years ago

Closed 4 years ago

#31580 closed Cleanup/optimization (fixed)

Union queryset should raise on distinct().

Reported by: Sielc Technologies Owned by: Hasan Ramezani
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords: orm, distinct, annotate, union
Cc: Hasan Ramezani Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description (last modified by Sielc Technologies)

After using

  • .annotate() on 2 different querysets
  • and then .union()
  • .distinct() will not affect the queryset
    def setUp(self) -> None:
        user = self.get_or_create_admin_user()

        Sample.h.create(user, name="Sam1")
        Sample.h.create(user, name="Sam2 acid")
        Sample.h.create(user, name="Sam3")
        Sample.h.create(user, name="Sam4 acid")

        Sample.h.create(user, name="Dub")
        Sample.h.create(user, name="Dub")
        Sample.h.create(user, name="Dub")

        self.user = user

    def test_union_annotated_diff_distinct(self):
        qs = Sample.objects.filter(user=self.user)
        qs1 = qs.filter(name='Dub').annotate(rank=Value(0, IntegerField()))
        qs2 = qs.filter(name='Sam1').annotate(rank=Value(1, IntegerField()))
        qs = qs1.union(qs2)
        qs = qs.order_by('name').distinct('name')  # THIS DISTINCT DOESN'T WORK
        self.assertEqual(qs.count(), 2)

expected to get wrapped union

    SELECT DISTINCT ON (siebox_sample.name) * FROM (SELECT ... UNION SELECT ...) AS siebox_sample

Change History (6)

comment:1 by Sielc Technologies, 4 years ago

Description: modified (diff)

comment:2 by Mariusz Felisiak, 4 years ago

Cc: Hasan Ramezani added
Easy pickings: set
Summary: Expect to get SELECT DISTINCT ON after UNION of 2 annotated QuerySetUnion queryset should raise on distinct().
Triage Stage: UnreviewedAccepted
Type: BugCleanup/optimization
Version: 3.0master

distinct() is not supported but doesn't raise an error yet. As ​per the documentation, "only LIMIT, OFFSET, COUNT(*), ORDER BY, and specifying columns (i.e. slicing, count(), order_by(), and values()/values_list()) are allowed on the resulting QuerySet.".

Follow up to #27995.

comment:3 by Hasan Ramezani, 4 years ago

Owner: changed from nobody to Hasan Ramezani
Status: newassigned

comment:4 by Hasan Ramezani, 4 years ago

Has patch: set

comment:5 by Mariusz Felisiak, 4 years ago

Triage Stage: AcceptedReady for checkin

comment:6 by GitHub <noreply@…>, 4 years ago

Resolution: fixed
Status: assignedclosed

In 01a381cc:

Fixed #31580 -- Added error messages on distinct() following union(), intersection(), and difference().

Note: See TracTickets for help on using tickets.
Back to Top