UNION ALL in Django Orm?

814 views
Skip to first unread message

cde...@predictivescience.com

unread,
Jun 17, 2016, 6:24:08 PM6/17/16
to Django users
I have two different queries on the same model that are in essence like this:

queryset_1 = models.Plan.object.filter(name__startswith='a').annotate(group=Value('Group A', output_field=CharField()))

queryset_2 = models.Plan.object.filter(name__startswith='b').annotate(group=Value('Group B', output_field=CharField()))

and when I try

queryset = queryset_1 | queryset_2

only one of those annotations appears to exist.  All rows returned have group set to "Group A" and when I inspect the sql it turns out that django only "or"-ing the filters.  It send something like:

SELECT plan_plan.*, "Group A" AS "group" FROM plan_plan WHERE ("plan_plan"."name" LIKE 'a%s' OR "plan_plan"."name" LIKE 'b%s');

Is there any way to get a true union instead of an or here?  I'm not particularly interested in using raw sql because in the actual application the filters are dynamic a considerably more complicated.

Thanks in advance,

Cameron Derwin

Ezequiel Bertti

unread,
Jun 17, 2016, 7:02:23 PM6/17/16
to django...@googlegroups.com
Take a look on this project 

https://github.com/Suor/django-union/

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f40d193e-3bd1-4489-af77-97bc529db264%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Reply all
Reply to author
Forward
0 new messages