티스토리 뷰

Django Framework

[DRF] StringRelatedField

lluna 2021. 11. 24. 00:24

수정전

{
    "username": "test1",
    "followings_count": 0,
    "followings": [],
    "followers_count": 1,
    "followers": [
        6
    ],
    "bookmarked_movies": [
        11
    ]
}

수정후 - followings, followers, bookmakared_movies 의 내용 출력

어떻게? Primary Key 대신 밸류값을 보내기 위해 StringRelatedField를 사용한다. '__str__' 메서드가 내부에 있다고 한다.

현재 User 모델에서 다대다 관계, Movie 모델에서 일대다 관계를 설정해주고 있기 때문에 적용이 가능하다.

class User(AbstractUser):
    followings = models.ManyToManyField('self', related_name='followers', symmetrical=False)
class Movie(models.Model):
    # 1:N
    year = models.ForeignKey(Year, on_delete=models.CASCADE, blank=True)
    # M:N
    genre_ids = models.ManyToManyField(Genre, related_name='movie_genre')
    # 이 영화를 북마크 한 사람
    bookmarked_users = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="bookmarked_movies")

    def __str__(self):
        return self.title
# 프로필 정보
# StringRelatedField
class ProfileSerializer(serializers.ModelSerializer):
    bookmarked_movies = serializers.StringRelatedField(many=True)
    followings = serializers.StringRelatedField(many=True)
    followers = serializers.StringRelatedField(many=True)
    followings_count = serializers.IntegerField(source='followings.count', read_only=True) # 유저 팔로워 수
    followers_count = serializers.IntegerField(source='followers.count', read_only=True)
    
    class Meta:
        model = get_user_model()
        fields = ('username', 'followings_count','followings','followers_count', 'followers','bookmarked_movies',)
{
    "username": "test1",
    "followings_count": 0,
    "followings": [],
    "followers_count": 1,
    "followers": [
        "test2"
    ],
    "bookmarked_movies": [
        "스타워즈: 에피소드 4 새로운 희망"
    ]
}

 

참고

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

 

Serializer relations - Django REST framework

 

www.django-rest-framework.org

https://stackoverflow.com/questions/55161052/instead-of-primary-key-send-different-field-in-django-rest-framework

 

Instead of Primary Key Send Different Field in Django REST Framework

serializers.py class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = [ 'popularity', 'director', 'genre', ...

stackoverflow.com

 

댓글