查询的关系的一侧的子集的多对多关系
问题描述:
假设我有Environment
和Animal
之间的多对多关系,与接合表看起来像:查询的关系的一侧的子集的多对多关系
environment_id animal_id
1 1
1 2
1 3
2 1
2 3
3 2
3 4
3 5
4 2
4 3
5 2
5 4
假设我有与一组Animal
小号ID (1,2,3)
,我如何查询数据库以仅返回与这些动物相关的动物子集的环境?在这个例子中,这将是Environments
与ID (1,2,4)
但不是3
或5
。 如果我尝试:
animals = Animal.objects.filter(id__in=(1,2,3))
animal_list = AnimalList.objects.filter(animal__in=animals)
显然,这并不工作,因为他们都从我的子集中的至少一种动物。
模型类主要有:
class Environment(models.Model):
name = models.CharField(max_length=250)
animals = models.ManyToManyField(Animal, through='AnimalList')
class Animal(models.Model):
name = models.CharField(max_length=200)
safe_around_david_cameron = models.BooleanField()
class AnimalList(models.Model):
environment = models.ForeighKey(Environment)
animal = models.ForeignKey(Animal)
可以添加模型类的代码? –