dynamic filter m2m field

27 views
Skip to first unread message

nat...@gmail.com

unread,
Mar 2, 2009, 4:59:09 PM3/2/09
to Django users
I'm trying to make a complex dynamic filter. The first thing I've done
is get dynamically a list of list of titles, something like this:

[[<Titulo: Diplomatura, Educación Infantil>, <Titulo: Diplomatura,
Educación>], [<Titulo: Idiomas, EGA>]]

and a way to add/remove list of titles to/from the general list (let's
call it big list).

Is there a way to filter a list of Persons that have Titles (m2m)
using AND in the big list and OR inside each little list?
In the example something like a person that have:

OR(<Titulo: Diplomatura, Educación Infantil>, <Titulo: Diplomatura,
Educación) AND(<Titulo: Idiomas, EGA>)

Thanks

Malcolm Tredinnick

unread,
Mar 2, 2009, 5:53:38 PM3/2/09
to django...@googlegroups.com

The key thing here are Q() objects. See [1] for the documentation. In
fact, under the covers, all filter() calls become Q() objects, so they
really are key.

You can combine Q's using & and | however you like. So wrapping each
item as a Q(title=some_title) and then putting them together, using a
loop or reduce() will do what you want.

[1]
http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

Regards,
Malcolm


nat...@gmail.com

unread,
Mar 3, 2009, 3:50:25 AM3/3/09
to Django users
I've done it intersecting the list of lists in pure python and then
calling the filter:

ml=[Persona.objects.filter(titulos__in=f).distinct() for f in
filtros]
tmp = {}
for l in ml:
for x in l:
z = tmp.get(x, [])
z.append(1)
tmp[x] = z
lQs = []
for k,v in tmp.items():
if len(v) == len(ml):
lQs.append(k.pk) # here I've got the list of intersected pks
lista=Persona.objects.filter(pk__in=lQs)

I'm sure it can be done in a more Django's way using Q, but don't know
how pass dynamical arguments... I've tryed with something like:

lQs=[Q(titulo__in=f) for f in filtros]
lista=Persona.objects.filter(lQs)

but doesn't work.


On 2 mar, 23:53, Malcolm Tredinnick <malc...@pointy-stick.com> wrote:
> [1]http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-looku...
>
> Regards,
> Malcolm
Reply all
Reply to author
Forward
0 new messages