django queryset for many-to-many field

时间:2022-09-02 20:14:48

I have the following Django 1.2 models:

我有以下Django 1.2模型:

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?

如何执行查询,该查询将为我提供与给定Preference对象相关的任何相同类别相关联的所有Article对象?

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

例如如果我有一个与“鱼”,“猫”和“狗”类别相关的偏好对象,我想要一个与“鱼”,“猫”或“狗”相关的所有文章的列表。

2 个解决方案

#1


17  

Try:

尝试:

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

#2


2  

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

#1


17  

Try:

尝试:

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

#2


2  

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