Programing

Django Rest Framework를 사용하여 관련 모델 필드를 어떻게 포함합니까?

crosscheck 2020. 6. 25. 08:15
반응형

Django Rest Framework를 사용하여 관련 모델 필드를 어떻게 포함합니까?


다음과 같은 모델이 있다고 가정 해 봅시다.

class Classroom(models.Model):
    room_number = [....]

class Teacher(models.Model):
    name = [...]
    tenure = [...]
    classroom = models.ForeignKey(Classroom)

ManyRelatedPrimaryKeyField 함수에 따라 다음과 같은 결과를 얻는 대신에

{
    "room_number": "42", 
    "teachers": [
        27, 
        24, 
        7
    ]
},

다음과 같이 전체 관련 모델 표현을 포함하는 것을 반환하십시오.

{
    "room_number": "42", 
    "teachers": [
        {
           'id':'27,
           'name':'John',
           'tenure':True
        }, 
        {
           'id':'24,
           'name':'Sally',
           'tenure':False
        }, 
    ]
},

이게 가능해? 그렇다면 어떻게? 그리고 이것은 나쁜 생각입니까?


가장 간단한 방법은 깊이 인수 를 사용 하는 것입니다

class ClassroomSerializer(serializers.ModelSerializer):
    class Meta:
        model = Classroom
        depth = 1

그러나 이는 선임 관계에 대한 관계 만 포함합니다.이 경우 교사 필드는 역 관계이기 때문에 필요한 것은 아닙니다.

더 복잡한 요구 사항이있는 경우 (예 : 역 관계 포함, 일부 필드 중첩, 다른 필드 제외) 또는 특정 필드 하위 집합 만 중첩하는 경우 serializer중첩 할 수 있습니다 .

class TeacherSerializer(serializers.ModelSerializer):
    class Meta:
        model = Teacher
        fields = ('id', 'name', 'tenure')

class ClassroomSerializer(serializers.ModelSerializer):
    teachers = TeacherSerializer(source='teacher_set')

    class Meta:
        model = Classroom

Note that we use the source argument on the serializer field to specify the attribute to use as the source of the field. We could drop the source argument by instead making sure the teachers attribute exists by using the related_name option on your Teacher model, ie. classroom = models.ForeignKey(Classroom, related_name='teachers')

One thing to keep in mind is that nested serializers do not currently support write operations. For writable representations, you should use regular flat representations, such as pk or hyperlinking.


Thank you @TomChristie!!! You helped me a lot! I would like to update that a little (because of a mistake I ran into)

class TeacherSerializer(serializers.ModelSerializer):
    class Meta:
        model = Teacher
        fields = ('id', 'name', 'tenure')

class ClassroomSerializer(serializers.ModelSerializer):
    teachers = TeacherSerializer(source='teacher_set', many=True)

    class Meta:
        model = Classroom
        field = ("teachers",)

This can also be accomplished by using a pretty handy dandy django packaged called drf-flex-fields. We use it and it's pretty awesome. You just install it pip install drf-flex-fields, pass it through your serializer, add expandable_fields and bingo (example below). It also allows you to specify deep nested relationships by using dot notation.

from rest_flex_fields import FlexFieldsModelSerializer

class ClassroomSerializer(FlexFieldsModelSerializer):
    class Meta:
        model = Model
        fields = ("teacher_set",)
    expandable_fields = {"teacher_set": (TeacherSerializer, {"source": "teacher_set"})}

Then you add ?expand=teacher_set to your URL and it returns an expanded response. Hope this helps someone, someday. Cheers!

참고URL : https://stackoverflow.com/questions/14573102/how-do-i-include-related-model-fields-using-django-rest-framework

반응형