I have 3 models:
JavaScript
x
25
25
1
class Airport(models.Model):
2
code = models.CharField(max_length=3)
3
city = models.CharField(max_length=64)
4
5
def __str__(self):
6
return f"{self.city} ({self.code})"
7
8
9
class Flight(models.Model):
10
origin = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="departures")
11
destination = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="arrivals")
12
duration = models.IntegerField( )
13
14
def __str__(self):
15
return f"{self.id}: {self.origin} to {self.destination}"
16
17
18
class Passenger(models.Model):
19
first = models.CharField(max_length=64)
20
last = models.CharField(max_length=64)
21
flights = models.ManyToManyField(Flight, blank=True, related_name="passengers")
22
23
def __str__(self):
24
return f"{self.first} {self.last}"
25
and I am trying to access all passengers of a certain Flight
when I visit /<int:flight_id>
like this:
JavaScript
1
9
1
def flight(request, flight_id):
2
flight = Flight.objects.get(id=flight_id)
3
# return HttpResponse(flight)
4
5
return render(request, "flights/flight.html", {
6
"flight": flight,
7
"passengers": Flight.passengers # AttributeError: 'ManyToManyDescriptor' object has no attribute 'all'
8
})
9
Your response is appreciated
Thank you In advanced
Advertisement
Answer
You can access passengers of an instance of Flight, not directly from class Flight:
JavaScript
1
9
1
def flight(request, flight_id):
2
flight = Flight.objects.get(id=flight_id)
3
# return HttpResponse(flight)
4
5
return render(request, "flights/flight.html", {
6
"flight": flight,
7
"passengers": flight.passengers.all() #here is 'flight' instead of 'Flight'
8
})
9