Paul Noon
Paul Noon

Reputation: 686

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

I use Django 1.9 and Python 2.7.

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".

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)

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

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

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

Upvotes: 1

Views: 988

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599698

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

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:

Picture.objects.filter(theplace__step__trip=selectedtrip)

Upvotes: 2

Related Questions