开发者

django queryset for many-to-many field

I have the following Django 1.2 models:

class Category(models.Model):
    name = models.CharField(max_length=25开发者_开发技巧5)

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


Try:

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜