django queryset为多对多领域 [英] django queryset for many-to-many field
本文介绍了django queryset为多对多领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下Django 1.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?
例如如果我有一个与鱼,猫和狗类别相关的偏好对象,我想要列出所有与鱼,猫或狗相关联的文章。 p>
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".
推荐答案
尝试:
preference = Preference.objects.get(**conditions)
Article.objects.filter(categories__in = preference.categories.all())
这篇关于django queryset为多对多领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文