Roger
Roger

Reputation: 5071

django queryset for many-to-many field

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".

Upvotes: 15

Views: 14931

Answers (2)

Dave Aaron Smith
Dave Aaron Smith

Reputation: 4567

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

Upvotes: 2

Manoj Govindan
Manoj Govindan

Reputation: 74675

Try:

preference = Preference.objects.get(**conditions)
Article.objects.filter(categories__in = preference.categories.all())

Upvotes: 18

Related Questions