Cannot resolve keyword 'vuelos' into field. Choices are: id, persona, persona_id, vuelo

Viewed 50

So i've been trying to do de CS50 airport app. When i try to exclude by the related_name it seems that takes "vuelos" as a field. Im not sure what can i do. This is apparently in the

non_pasajeros=Pasajero.objects.exclude(vuelos=vuelo).all()

line on views.py, while i'm trying to exclude vuelos as the Pasajero related_name, the error says there is not vuelos keyword on the field.

this is models.py

from django.db import models
from django.db.models.deletion import CASCADE
from django.db.models.fields import BLANK_CHOICE_DASH

# Create your models here.
class Aeropuerto(models.Model):
    codigo = models.CharField(max_length=3)
    ciudad = models.CharField(max_length=64)

    def __str__(self):
        return f"{self.codigo} - {self.ciudad}"
class Persona(models.Model):
    nombres = models.CharField(max_length=64)
    apellidos = models.CharField(max_length=64) 

    def __str__(self):
        return f"{self.nombres} {self.apellidos}"
class Vuelo(models.Model):
    origen = models.ForeignKey(Aeropuerto, on_delete=models.CASCADE, related_name="salidas")
    destino = models.ForeignKey(Aeropuerto, on_delete=models.CASCADE, related_name="llegadas")
    duracion = models.IntegerField()

    def __str__(self):
        return f"{self.id}: {self.origen} a {self.destino}"
class Pasajero(models.Model):
    persona = models.ForeignKey(Persona, on_delete=CASCADE, related_name="vuelos")
    vuelo = models.ManyToManyField(Vuelo, blank=True, related_name="pasajeros")

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

this is views.py

from django.http.response import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .models import Persona, Vuelo, Pasajero

# Create your views here.

def index(request):
    return render(request, "vuelos/index.html", {
        "vuelos": Vuelo.objects.all()
    })

def pasajeros(request):
    return render(request, "pasajeros/pasajeros.html", {
        "pasajeros":Pasajero.objects.all()
    })

def vuelos(request, vuelo_id):
    vuelo=Vuelo.objects.get(id=vuelo_id)
    pasajeros=vuelo.pasajeros.all()
    non_pasajeros=Pasajero.objects.exclude(vuelos=vuelo).all()
    return render(request, "vuelos/vuelos.html", {
        "vuelo":vuelo,
        "pasajeros":pasajeros,
        "non_pasajeros": non_pasajeros,
    })

def reserva(request, vuelo_id):
    if request.method == "POST":
        vuelo=Vuelo.objects.get(pk=vuelo_id)
        pasajero_id=int(request.POST["pasajero"])
        pasajero=Pasajero.objects.get(pk=pasajero_id)
        pasajero.vuelos.add(vuelo)
        return HttpResponseRedirect(reverse("vuelo", args=vuelo.id))

this is the error Traceback

    Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/vuelos/1

Django Version: 3.2.6
Python Version: 3.9.6
Installed Applications:
['vuelos',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Usuario\Desktop\BETO PROG\aerolinea\vuelos\views.py", line 21, in vuelos
    non_pasajeros=Pasajero.objects.exclude(vuelos=vuelo).all()
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 949, in exclude
    return self._filter_or_exclude(True, args, kwargs)
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 961, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 966, in _filter_or_exclude_inplace
    self._query.add_q(~Q(*args, **kwargs))
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1393, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1412, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1286, in build_filter
    lookups, parts, reffed_expression = self.solve_lookup_type(arg)
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1112, in solve_lookup_type
    _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1539, in names_to_path
    raise FieldError("Cannot resolve keyword '%s' into field. "

Exception Type: FieldError at /vuelos/1
Exception Value: Cannot resolve keyword 'vuelos' into field. Choices are: id, persona, persona_id, vuelo
1 Answers

The name of the field is vuelo, indeed, in the model this ManyToManyField is defined as:

class Pasajero(models.Model):
    # …
    vuelo = models.ManyToManyField(Vuelo, blank=True, related_name='pasajeros')

This thus means that we can work with the vuelo field, not the vuelos. The queryset thus looks like:

non_pasajeros=Pasajero.objects.exclude(vuelo=vuelo)
Related