Django:获取多个表时的KeyError

时间:2018-03-31 12:39:01

标签: django

我刚接触Django,我需要从多个表中获取列,所以我尝试了这个:

class OffreViewSet(ModelViewSet):
queryset = Offre.objects.filter(idRecruteur=1).values('dateAjout','idRecruteur__entrepriseName')

serualizers.py

class OffreSerializer(serializers.ModelSerializer):

    class Meta:
        model = Offre
        fields = '__all__'

models.py

@python_2_unicode_compatible
class Recruteur(models.Model):  
    recruteur_id = models.AutoField(primary_key=True,verbose_name="Recruteur id")       
name = models.CharField(max_length=50)
lastName = models.CharField(max_length=50)
email = models.CharField(max_length=50)         
    entrepriseName = models.CharField(max_length=50)
    def __str__(self):
        return "Recruteur: {}".format(self.recruteur_id)

@python_2_unicode_compatible
class Offre(models.Model):          
    title = models.CharField(max_length=100, blank=True, default=0)
dateAjout = models.DateField(auto_now=False, auto_now_add=False)
nature = models.CharField(max_length=50)
    idRecruteur = models.ForeignKey(Recruteur,verbose_name = "recruteur", on_delete=models.CASCADE)
    def __str__(self):
        return "Offre: {}".format(self.title)

我需要从表格' Offre'输出 dateAjout 。表格' Recruteur'中的 entrepriseName 但是django提出了一个 KeyError:' idRecruteur' 。 这也是追溯:

    Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/scrumboard/Offres/

Django Version: 2.0.2
Python Version: 3.4.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'corsheaders',
 'scrumboard']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\djangular\lib\site-packages\django\core\handlers\exception.py" in inner
  35.             response = get_response(request)

File "C:\djangular\lib\site-packages\django\core\handlers\base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "C:\djangular\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\djangular\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "C:\djangular\lib\site-packages\rest_framework\viewsets.py" in view
  95.             return self.dispatch(request, *args, **kwargs)

File "C:\djangular\lib\site-packages\rest_framework\views.py" in dispatch
  494.             response = self.handle_exception(exc)

File "C:\djangular\lib\site-packages\rest_framework\views.py" in handle_exception
  454.             self.raise_uncaught_exception(exc)

File "C:\djangular\lib\site-packages\rest_framework\views.py" in dispatch
  491.             response = handler(request, *args, **kwargs)

File "C:\djangular\lib\site-packages\rest_framework\mixins.py" in list
  48.         return Response(serializer.data)

File "C:\djangular\lib\site-packages\rest_framework\serializers.py" in data
  742.         ret = super(ListSerializer, self).data

File "C:\djangular\lib\site-packages\rest_framework\serializers.py" in data
  262.                 self._data = self.to_representation(self.instance)

File "C:\djangular\lib\site-packages\rest_framework\serializers.py" in to_representation
  660.             self.child.to_representation(item) for item in iterable

File "C:\djangular\lib\site-packages\rest_framework\serializers.py" in <listcomp>
  660.             self.child.to_representation(item) for item in iterable

File "C:\djangular\lib\site-packages\rest_framework\serializers.py" in to_representation
  491.                 attribute = field.get_attribute(instance)

File "C:\djangular\lib\site-packages\rest_framework\relations.py" in get_attribute
  177.         return get_attribute(instance, self.source_attrs)

File "C:\djangular\lib\site-packages\rest_framework\fields.py" in get_attribute
  98.                 instance = instance[attr]

Exception Type: KeyError at /scrumboard/Offres/
Exception Value: 'idRecruteur'

Settings.py:

"""
Django settings for djangular project.

Generated by 'django-admin startproject' using Django 2.0.2.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'k%sdbos%2vqcd*0*=6gc+4lr%ygj&5o46%df2@&(c17hy=e@q$'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'scrumboard',
]


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True

ROOT_URLCONF = 'djangular.urls'

TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'djangular.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'

我做错了什么?

2 个答案:

答案 0 :(得分:0)

extension Array { mutating func removeAtIndexes(indexes: IndexSet) { var i:Index? = indexes.last while i != nil { self.remove(at: i!) i = indexes.integerLessThan(i!) } } } 需要指向idRecruter的实际模型而不仅仅是id。所以这应该有效:

Recruter

答案 1 :(得分:0)

&mut self

Django在Table中创建id,因此你必须在其中使用ID。