views:

242

answers:

1

I'd like to find how to select all objects whose ManyToMany field contains another object. I have the following models (stripped down)

class Category(models.Model):
    pass

class Picture(models.Model):
    categories = models.ManyToManyField(Category)
    visible = models.BooleanField()

I need a function to select all the Pictures in one or more Categories:

def pics_in_cats(cat_ids=()):
    pass

BUT it needs to return a QuerySet if possible so that I can do something like:

pics_in_cats((1,2,3)).filter(visible=True)

It could be done by loading all the relevant Category objects and merging their picture_set attributes, but that seems inefficient. I'd also like to avoid falling back to raw SQL if possible.

Thanks in advance

+1  A: 

Why write a custom function and not use something like this? (untested)

pics = Picture.objects.filter(categories__in = [1,2,3]).filter(visible=True)
schneck
That works - but I'm not sure why :)Is that saying 'where any category primary key matches any of 1,2,3'?And could I say filter(categories__name__in=['foo','bar']) for example to get all pictures in categories with name foo or bar?
Aaron Lockey
that's correct. To see all possibilities you have in Django building queries, have a look here:http://docs.djangoproject.com/en/dev/topics/db/queries/
schneck