代码之家  ›  专栏  ›  技术社区  ›  Ishaan Dabhade

访问related_name时,“ManyToManyDescriptor”对象没有属性“all”

  •  0
  • Ishaan Dabhade  · 技术社区  · 3 年前

    我有三个模型:

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

    我正试图联系某航班的所有乘客 Flight 当我访问 /<int:flight_id> 这样地:

    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'
        })
    

    感谢您的回复

    提前谢谢

    0 回复  |  直到 3 年前
        1
  •  0
  •   HuLu ViCa    3 年前

    您可以访问 乘客 一个实例 航班 ,不是直接来自课堂 航班 :

    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'
        })