Django - Follow a backward ForeignKey and then a ForeignKey (query)
<p>I use Django 1.9 and Python 2.7.</p>

<p>My app has four models. Each "trip" is made of several "steps" chosen by the visitor, which relate to "places", which may have several related "Picture".</p>

<pre><code>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)
</code></pre>

<p>I would like to retrieve all "Picture" objects which are related to a specific Trip, using an existing "selectedtrip" queryset:</p>

<pre><code>selectedtrip = Trip.objects.filter(author=request.user)[0]
pictures = selectedtrip.step_set.all().theplace.picture_set.all()
</code></pre>

<p>Django displays the following error:
"AttributeError: 'QuerySet' object has no attribute 'theplace'"
Any idea why ?</p>

<p>Because <code>all()</code> returns a queryset, which is a collection of items; <code>theplace</code> is an attribute on an individual Step, not on the collection.</p>

<p>The way to do this type of query is to start from the class you want to retrieve, and follow the relationships within the query using the double-underscore syntax. So:</p>

<pre><code>Picture.objects.filter(theplace__step__trip=selectedtrip)
</code></pre>

python django django-models foreign-keys django-queryset