Skip to content
Advertisement

‘ManyToManyDescriptor’ object has no attribute ‘all’ when accessing related_name

I have 3 models:

class Airport(models.Model):
    code = models.CharField(max_length=3)
    city = models.CharField(max_length=64)

    def __str__(self):
        return f"{self.city} ({self.code})"


class Flight(models.Model):
    origin = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="departures")
    destination = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="arrivals")
    duration = models.IntegerField( )

    def __str__(self):
        return f"{self.id}: {self.origin} to {self.destination}"


class Passenger(models.Model):
    first = models.CharField(max_length=64)
    last = models.CharField(max_length=64)
    flights = models.ManyToManyField(Flight, blank=True, related_name="passengers")

    def __str__(self):
        return f"{self.first} {self.last}"

and I am trying to access all passengers of a certain Flight when I visit /<int:flight_id> like this:

def flight(request, flight_id):
    flight = Flight.objects.get(id=flight_id)
    # return HttpResponse(flight)

    return render(request, "flights/flight.html", {
        "flight": flight,
        "passengers": Flight.passengers # AttributeError: 'ManyToManyDescriptor' object has no attribute 'all'
    })

Your response is appreciated

Thank you In advanced

Advertisement

Answer

You can access passengers of an instance of Flight, not directly from class Flight:

def flight(request, flight_id):
    flight = Flight.objects.get(id=flight_id)
    # return HttpResponse(flight)

    return render(request, "flights/flight.html", {
        "flight": flight,
        "passengers": flight.passengers.all() #here is 'flight' instead of 'Flight'
    })
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement