Use DRF Serializers Effectively in Django

JunePyo Suh·2020년 9월 13일
0

Using source argument

When used fittingly, source simplifies a lot of common patterns.

Serializing to different keys

To serialize username field to user_name key, add a CharField on the serializer with a source attribute.

    user_name = serializers.CharField(source='username')

Serializing model methods

If user models has a method called get_full_name, you can also use it as an argument for source.

    full_name = serializers.CharField(source='get_full_name')

Assume there is a Profile model which has a OneToOne relationship with User.

street = serializers.CharField(source='profile.street')
city = serializers.CharField(source='profile.city')

If we want the id and name for each group associated with the user, we write a GroupSerializer and include it in UserSerializer.

class UserSerializer(serializers.ModelSerializer):

    all_groups = GroupSerializer(source='groups', many=True)

    class Meta:
        model = User
        fields = ('email', 'first_name', 'last_name', 'all_groups')

This is more DRFish way to add all_groups field instead of defining another SerializerMethodField and add user.groups.all() in the method.

Using SerializerMethodField

SerializerMethodField is useful when we need to run custom code during serialization of a particular field, such as String manipulation or setting groups as None instead of an empty list if no groups are associated with the user.

    def get_groups(self, obj):
        groups = obj.groups.all()
        if not groups:
            return None
        return GroupSerializer(groups, many=True).data

Using to_representation

If we wish to add a key called admin to serialized data only when the user is a superuser,

 def to_representation(self, instance):
        representation = super().to_representation(instance)
        if instance.is_superuser:
            representation['admin'] = True
        return representation

Original article on medium

0개의 댓글