> I'd like to make a filter composed by ORing several Q objects, each of
> which acts on a different model field.
> For example I have a model with the fields "name", "title",
> "description" and I want to make a Q object like the following:
> Q_name = (Q(name__istartswith="hello") & Q(name__icontains="how are
> you"))
> Q_title = (Q(title__istartswith="hello") & Q(title__icontains="how are
> you"))
> Q_description = (Q(description__istartswith="hello") &
> Q(description__icontains="how are you"))
> Q_final = (Q_name | Q_title | Q_description)
>
> Is it possible to avoid writing a Q object for each field and instead
> simply generate it by passing the field (name, title and description)
> as parameter?
Just as an aside, the Q object takes multiple parameters that get
AND'ed together, so those can be written in the form
Q_name = Q(
name__istartswith='hello',
name__icontains='how are you'
)
without the need for two diff. objects to "&" together.
You can write a helper function and then use keyword expansion to
do the heavy lifting if you wanted. That would look something like
def start_has(fieldname, start, contain):
return {
fieldname + '__istartswith': start,
fieldname + '__icontains': contain,
}
Q_name = Q(**start_has('name', 'hello', 'how are you'))
Q_description = Q(**start_has('description', 'hello', 'how are
you'))
Q_title = Q(**start_has('name', 'title', 'how are you'))
If this is within a view, you can even exploit closures (I think
this is a use of a closure) to do something like
def my_view(request, *args, **kwargs):
start = 'hello' # assign from request
has = 'how are you' # assign from request
def start_has(fieldname):
return {
fieldname + '__istartswith': start,
fieldname + '__icontains': has,
}
things = models.Thing.objects.filter(
Q(**start_has('name')) |
Q(**start_has('title')) |
Q(**start_has('description'))
)
The above is 100% untested, but should work from what I've done
with Python/Django in the past, perhaps with a few lurking
errors I might have missed.
-tim
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---