티스토리 뷰

수정전

{
    "id": 20,
    "content": "1",
    "rank": 5,
    "created_at": "2021-11-22T21:25:09.710518",
    "updated_at": "2021-11-22T21:25:09.710546",
    "user": 5,
    "movie": 13
}

수정후 - user 이름을 출력

# 리뷰 상세
class UsernameSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ('id', 'username',)
        
class ReviewSerializer(serializers.ModelSerializer):
    user = UsernameSerializer(read_only=True)
    
    class Meta:
        model = Review
        fields = '__all__'
        read_only_fields = ('movie', 'user',)
{
    "id": 30,
    "user": {
        "id": 5,
        "username": "test1"
    },
    "content": "sgadg",
    "rank": 3,
    "created_at": "2021-11-22T21:38:36.478712",
    "updated_at": "2021-11-23T23:55:17.863929",
    "movie": 14
}

 

참고

https://stackoverflow.com/questions/38316321/change-a-field-in-a-django-rest-framework-modelserializer-based-on-the-request-t

 

Change a field in a Django REST Framework ModelSerializer based on the request type?

Consider this case where I have a Book and Author model. serializers.py class AuthorSerializer(serializers.ModelSerializer): class Meta: model = models.Author fields = ('id', '

stackoverflow.com

https://www.django-rest-framework.org/api-guide/relations/#nested-relationships

 

Serializer relations - Django REST framework

 

www.django-rest-framework.org

 

댓글