0

Iam new to Django and i need to fetch columns from multiple tables, so i tried this:

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)

I need to output both dateAjout from table 'Offre' and entrepriseName from table 'Recruteur' but django raises a KeyError: 'idRecruteur'. This is the traceback as well:

    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/'

What am i doing wrong ?

7
  • I don't think your KeyError is raising from that particular ORM. Please add your traceback as well Commented Mar 31, 2018 at 12:53
  • Please post all the code you are using. The traceback is from Django rest framework. Why do we have to guess the source of your issue? Commented Mar 31, 2018 at 13:29
  • Sorry for that, i added the serializer.py and settings.py Commented Mar 31, 2018 at 13:58
  • I am sure, your code above is right, error is most probably either from your serializer or you are trying to access idRecruteur where it is not accessible. Commented Mar 31, 2018 at 15:05
  • How this can be from the serializer ? Commented Mar 31, 2018 at 15:13

2 Answers 2

0

idRecruter needs to point to an actual model of Recruter not just the id. So this should work:

recruter_1 = Recruter.objects.get(id=1) # can also use pk=1
queryset = Offre.objects.filter(idRecruteur=recruter_1).values('dateAjout','idRecruteur__entrepriseName')
Sign up to request clarification or add additional context in comments.

Comments

0
queryset = Offre.objects.filter(idRecruteur_id=1).values('dateAjout','idRecruteur__entrepriseName')

Django Create id in Table so you have to use ID in it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.