Django - 遵循向后的外键,然后是外键(查询)

Django - Follow a backward ForeignKey and then a ForeignKey (query)

我使用 Django 1.9 和 Python 2.7.

我的应用程序有四个模型。每个"trip"是由访问者选择的几个"steps"组成的,这些"steps"与"places"相关,可能有几个相关的"Picture".

class Trip(models.Model):
    title = models.CharField(max_length=140, blank=True)

class Step(models.Model):
    theplace = models.ForeignKey(ThePlace)
    trip = models.ForeignKey(Trip)

class ThePlace(models.Model):
    name = models.CharField(max_length=200)

class Picture(models.Model):
    file = models.ImageField(upload_to="pictures")
    slug = models.SlugField(max_length=100, blank=True)
    theplace = models.ForeignKey(ThePlace, null=True, blank=True)

我想检索与特定旅行相关的所有 "Picture" 个对象,使用现有的 "selectedtrip" 查询集:

selectedtrip = Trip.objects.filter(author=request.user)[0]
pictures = selectedtrip.step_set.all().theplace.picture_set.all()

Django 显示以下错误: "AttributeError: 'QuerySet' object has no attribute 'theplace'" 知道为什么吗?

因为all() returns一个查询集,它是一个项目的集合; theplace 是单个步骤的属性,而不是集合的属性。

执行此类查询的方法是从要检索的 class 开始,并使用双下划线语法遵循查询内的关系。所以:

Picture.objects.filter(theplace__step__trip=selectedtrip)