pythondjangoserializationdjango-rest-frameworkdjango-related-manager

DRF, get foreignkey objects using option


I'm trying to make backend using DRF, and I just faced a problem.

models.py:

class SchoolYear(models.Model):
    title = models.CharField(max_length=255, unique=True)

class Student(models.Model):
    name = models.CharField(max_length=10)
    school_year = models.ForeignKey(
        "students.SchoolYear",
        related_name="school_year",
        on_delete=models.CASCADE,
    )


class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = '__all__'

Result from POSTMAN when using the option.


{
    "name": "Student Signup",
    "description": "",
    "renders": [
        "application/json",
        "text/html"
    ],
    "parses": [
        "application/json",
        "application/x-www-form-urlencoded",
        "multipart/form-data"
    ],
    "actions": {
        "POST": {
            "name": {
                "type": "string",
                "required": true,
                "read_only": false,
            },
            "school_year": {
                "type": "field",
                "required": true,
                "read_only": false,
            }
        }
    }
}

But I want to get a result like this. Because I have to deliver this to the front-end developer to make select form.

I'd like to use this method, so I'd appreciate it if you could let me know if there's any other good method.

{
    "name": "Student Signup",
    "description": "",
    "renders": [
        "application/json",
        "text/html"
    ],
    "parses": [
        "application/json",
        "application/x-www-form-urlencoded",
        "multipart/form-data"
    ],
    "actions": {
        "POST": {
            "name": {
                "type": "string",
                "required": true,
                "read_only": false,
            },
            "school_year": [
                    {
                        "id" : 1,
                        "title": "title1",
                    },
                    {
                        "id" : 2,
                        "title": "title2",
                    },
                    {
                        "id" : 3,
                        "title": "title3",
                    },
                    {
                        "id" : 4,
                        "title": "title4",
                    }
                ]
        }
    }
}


Solution

  • Try this:

    class StudentSerializer(serializers.ModelSerializer):
        school_year_title = serializers.CharField(source='schoolyear.title')
        school_year_id = serializers.CharField(source='schoolyear.id')
        class Meta:
            model = Student
            fields = ('name','school_year_title','school_year_id'
    

    This should do the trick .

    You can take a look here:

    https://www.django-rest-framework.org/api-guide/fields/#source