django视图限制子查询

时间:2013-12-23 12:52:25

标签: python django django-views

我有3个型号: models.py:

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

class Musician(models.Model):
    person = models.ForeignKey(Person)
    instrument = models.CharField(max_length=100)

class Album(models.Model):
    artist = models.ForeignKey(Musician)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()

我正在尝试构建一个视图: 显示所有人的专辑,不包括那些评为1星的ALBUMS。 views.py:

inner_qs = Musician.objects.filter(Album__num_stars__exact=1).values_list('person', flat=True).distinct()
person_list = Person.objects.exclude(Musician__Album__id__in=inner_qs).distinct()

查询离开排除了所有可能拥有1星级专辑的艺术家。 我需要在SQL上看起来像这样的东西:

SELECT p.first_name, p.last_name,m.instrument, m.name, m.num_stars
    FROM Person p
  INNER JOIN Musician m ON m.person = p.id
  INNER JOIN Album a ON a.artist = m.id
      WHERE m.num_stars <> 1

我知道视图在Person级别被排除,但是如何将元素进一步排除到db模型中?

谢谢!

2 个答案:

答案 0 :(得分:2)

如果您需要来自链接对象的所有字段数据(结果sql将与您需要的类似):

Album.objects.filter(~Q(num_stars=1)).select_related()

只有个人数据:

Person.objects.filter(~Q(musician__album__num_stars=1))

答案 1 :(得分:1)

Person.objects.filter(Musician__Album__num_stars__exact=1).values_list('person', flat=True).distinct()

导致sql结果相同:

SELECT DISTINCT p.first_name, p.last_name,m.instrument, m.name, m.num_stars
    FROM Person p
    INNER JOIN Musician m ON m.person = p.id
    INNER JOIN Album a ON a.artist = m.id
    WHERE m.num_stars <> 1