▷ 장고 DRF 특강 (9) // feat. 복습
1. serializer 복습
- 외래 키 관계에 있는 테이블이 있을 경우, 해당 테이블의 serializer를 생성해 함께 사용
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = "__all__"
class UserSerializer(serializers.ModelSerializer):
"""
외래 키는 UserProfile에서 User 테이블로 설정되어 있지만
one to one 필드기 때문에 userprofile이라는 명칭으로 역참조가 가능하다.
"""
userprofile = UserProfileSerializer()
class Meta:
model = User
fields = ["username", "password", "fullname", "email", "userprofile"]
- SerializerMethodField를 활용해 원하는 필드를 추가하고, 더 나아가서 여러 serializer들을 함께 사용
class HobbySerializer(serializers.ModelSerializer):
# serializers.SerializerMethodField()를 사용해 원하는 필드를 생성한다.
same_hobby_users = serializers.SerializerMethodField()
def get_same_hobby_users(self, obj):
user_list = []
for user_profile in obj.userprofile_set.all():
user_list.append(user_profile.user.username)
return user_list
class Meta:
model = Hobby
fields = ["name", "same_hobby_users"]
class UserProfileSerializer(serializers.ModelSerializer):
# 외래 키 관계로 이어져 있는 필드는 Serializer를 바로 호출할 수 있다.
hobby = HobbySerializer(many=True)
class Meta:
model = UserProfile
fields = "__all__"
class UserSerializer(serializers.ModelSerializer):
# One-to-one 관계에서는 fk처럼 사용 가능하다.
userprofile = UserProfileSerializer()
class Meta:
model = User
fields = ["username", "password", "fullname", "email", "userprofile"]
# views.py
...
class UserView(APIView)
def get(self, request):
user = request.user
return Response(UserSerializer(user).data, status=status.HTTP_200_OK)
# response data
"""
{
"username": "admin",
"password": "pbkdf2_sha256$320000$u5YnmKo9luab9csqWpzRsa$pKfqHnBiF5Rgdo1Mj9nxNOdhpAl9AhPVXFPXkbPz7Mg=",
"fullname": "zxcv",
"email": "zxv@asd.com",
"userprofile": {
"birthday": "2022-06-08",
"age": 1,
"introduction": "asdac",
"hobby": [
{
"name": "독서",
"same_hobby_users": [
"user1",
"user2",
"user3"
]
}
]
}
}
"""
'개발_TIL' 카테고리의 다른 글
개발_TIL | 2022-06-29 (50) (0) | 2022.07.06 |
---|---|
개발_TIL | 2022-06-28 (49) (0) | 2022.06.28 |
개발_TIL | 2022-06-24 (47) (0) | 2022.06.28 |
개발_TIL | 2022-06-23 (46) (0) | 2022.06.28 |
개발_TIL | 2022-06-22 (45) (0) | 2022.06.28 |