views:

49

answers:

2

I have the following Django 1.2 models:

class Category(models.Model):
    name = models.CharField(max_length=255)

class Article(models.Model):
    title = models.CharField(max_length=10, unique=True)
    categories = models.ManyToManyField(Category)

class Preference(models.Model):
    title = models.CharField(max_length=10, unique=True)
    categories = models.ManyToManyField(Category)

How can I perform a query that will give me all Article objects that are associated with any of the same categories that a given Preference object is related with?

e.g. If I have a Preference object that is related to categories "fish", "cats" and "dogs", I want a list of all Articles that are associated with any of "fish", "cats" or "dogs".

A: 

This should work.

Article.objects.filter(categories__in=myPreferenceObject.categories)

Edit Right right, sorry about that.

Article.objects.filter(categories__in=myPreferenceObject.categories.all())
Dave Aaron Smith
Did you test that out? I tried something similar and got an error.
Manoj Govindan
I get a TypeError: 'ManyRelatedManager' object is not iterable
Roger
My fault. Fixed.
Dave Aaron Smith
A: 

Try:

preference = Preference.objects.get(**conditions)
Article.objects.filter(categories__in = preference.categories.all())
Manoj Govindan
yeah, this works.
Roger