Django过滤两次嵌套实例

时间:2018-03-02 11:29:34

标签: django

以下是我的模型示例:

class Section(models.Model):
   name = models.CharField(max_length=255)


class Album(models.Model):
   name = models.CharField(max_length=255)
   model1 = models.ManyToManyField(Section, on_delete=models.CASCADE,
 related_name='model2')



class Image(models.Model):
   name = models.CharField(max_length=255)
   active = models.BooleanField(default=True)
   model2 = models.ManyToManyField(Album, on_delete=models.CASCADE,
related_name='model3')

我正在尝试查找所有包含图片且活动字段= False

的相册
Section.object.filter(albums__images__active=False)

但即使他们的字段有效= True

,我也会收到所有图片

1 个答案:

答案 0 :(得分:0)

无论如何,你的模型缺乏可读性,所以我假设你的模型类似于下面的内容,

class Section(models.Model):
    name = models.CharField(max_length=255)


class Album(models.Model):
    name = models.CharField(max_length=255)
    genre = models.ManyToManyField(Section, on_delete=models.CASCADE, related_name='genre')


class Image(models.Model):
    name = models.CharField(max_length=255)
    active = models.BooleanField(default=True)
    field_new = models.ManyToManyField(Album, on_delete=models.CASCADE, related_name='field_new')


如果是这样,可能的回答是,

section_queryset = Section.objects.filter(genre__isnull=False, genre__field_new__isnull=False, genre__field_new__active=False)