簡體   English   中英

DRF,使用選項獲取外鍵對象

[英]DRF, get foreignkey objects using option

我正在嘗試使用 DRF 制作后端,但我遇到了一個問題。

模型.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__'

使用該選項時來自 POSTMAN 的結果。


{
    "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,
            }
        }
    }
}

但我想得到這樣的結果。 因為我必須將其交付給前端開發人員以制作 select 表格。

我想用這個方法,所以如果你能告訴我是否還有其他好的方法,我將不勝感激。

{
    "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",
                    }
                ]
        }
    }
}

嘗試這個:

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'

這應該可以解決問題。

你可以在這里看看:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM