Wednesday, August 1, 2012

Re: union of two QuerySets

On 1 elo, 19:15, Tim Chase <django.us...@tim.thechases.com> wrote:
> On 08/01/12 10:28, lex P rez wrote:
>
> > Hi,
>
> > it's better  Person.objects.filter(models.Q(first_**name__startswith='mic'),
> > models.Q(first_**name__startswith='joh'))
> > (only one query...)
>
> I'm pretty sure this will get you the intersection (it uses AND)
> rather than the union (which would be using OR).  So I think you want
>
>  from django.db.models import Q
>  Person.objects.filter(
>    Q(first_name__startswith="mic") |
>    Q(first_name__startswith="joh")
>    )
>
> using the "|" (OR) operator to join the two Q objects.
>
> -tkc
>
> For reference, you can read at
>
> https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db...
>
> https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-look...

As stated earlier the correct way to combine two existing querysets is
to do: combined = qs1 | qs2.

There are some limitations to what kind of querysets will work, but
for plain querysets which have just filers applied things should just
work.

- Anssi

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment