M
M
Mike2018-09-04 11:16:54
Django
Mike, 2018-09-04 11:16:54

How to display what level'u the question belongs to?

I am using DRF. I have two models. Level and Question. When I make a GET request to 'localhost:8000/api/questions/' I get "level: (the id is displayed here, but I would like to get the name of the level).
Here:

{
    "en": "she is a girl",
    "ru": "она девочка",
    "level": 1
  },
  {
    "en": "hi friend",
    "ru": "привет друг",
    "level": 2
  },

models.py
from django.db import models

class Level(models.Model):

    level = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=50, unique=True)

    def __str__(self):
        return self.level

class Question(models.Model):

    en = models.CharField(max_length=255)
    ru = models.CharField(max_length=255)
    btn = models.TextField()
    level = models.ForeignKey(Level, related_name='question', on_delete=models.CASCADE)

    def __str__(self):
        return self.en

serializers.py
from . models import Level, Question
from rest_framework import serializers

class LevelSerializer(serializers.ModelSerializer):

    question = serializers.StringRelatedField(many=True)

    class Meta:

        model = Level
        fields = ('level', 'question',)

class QuestionSerializer(serializers.ModelSerializer):

    class Meta:

        model = Question
        fields = ('en', 'ru', 'level')

How can I get the names of my levels in a GET request instead of their id ? That is, it should be something like this:
{
    "en": "she is a girl",
    "ru": "она девочка",
    "level": "number one"
  },
  {
    "en": "hi friend",
    "ru": "привет друг",
    "level": "number two"
  },

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2018-09-04
@deliro

1. SerializerMethodField
2. get_FOO_display

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question