如何在Django REST框架中实现嵌套序列化器

u5i3ibmn  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(105)

我正在尝试实现嵌套的序列化器。
Serializers.py

class BranchSerializer(serializers.ModelSerializer):

    class Meta:
        model = Branch
        fields = '__all__'

class StudentSerializer(serializers.ModelSerializer):

    class Meta:
        model = Student
        fields = '__all__'

重写studentserializers中的分支并导入分支详细信息。

jjjwad0x

jjjwad0x1#

class BranchSerializer(serializers.ModelSerializer):
    class Meta:
        model = Branch
        fields = '__all__'

class StudentSerializer(serializers.ModelSerializer):

    branch = serializers.PrimaryKeyRelatedField(queryset=Branch.objects.all())

    # to get single field name.
    # branch = serializers.CharField(source = 'branch.branch_name') 

    class Meta:
        model = Student
        fields = '__all__'

相关问题