Thursday, May 29, 2014

Re: How to concatenate a list of Q objects?

from django.db.models import Q
import operator

qs = SomeModel.objects.all()

# use reduce
rules = []
for rule_key, rule_value in calculated_rules:
    rules.append(Q(rule_key=rule_value))

if rules:
    qs = qs.filter(reduce(operator.or_, rules))

# not use it
q_collect = None
for rule_key, rule_value in calculated_rules:
    new_q = Q(rule_key=rule_value)
    if q_collect is None:
        q_collect = new_q
    else:
        q_collect = q_collect | new_q

if rules:
    qs = qs.filter(q_collect)

вторник, 6 апреля 2010 г., 9:10:08 UTC+4 пользователь Daniel написал:
Hi, I think that this must be super easy, but I'm kind of stumped.

I have a list qObjects = [qObject1, qObject2, qObject3]
What I'd like is to form this query:  Sample.objects.filter(qObject1,
qObject2, qObject3)

How would I accomplish what I need?  Thanks!

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/80a976f7-6591-4ed8-9cb8-399f986d41df%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment