Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 992
Roger Avatar asked Sep 02 '10 19:09

Roger


1 Answers

Try:

preference = Preference.objects.get(**conditions)
Article.objects.filter(categories__in = preference.categories.all())
like image 164
Manoj Govindan Avatar answered Nov 07 '22 05:11

Manoj Govindan