[Answered ]-Users are not saving in ManyToMany Field drf

1👍

At first, modify the users field as a ListField with a child CharField, so that you can pass a list of usernames as input.

Additionally, use to_representation() method to return a list of usernames instead of a ManyRelatedManager object so:

class BlogSerializer(serializers.ModelSerializer):
    users = serializers.ListField(child=serializers.CharField())

    class Meta:
        model = Blog
        fields = "__all__"

    def create(self, validated_data):
        user_usernames = validated_data.pop('users', [])
        blog = Blog.objects.create(**validated_data)
        users = User.objects.filter(username__in=user_usernames)
        blog.users.set(users)
        return blog

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['users'] = list(instance.users.all().values_list('username', flat=True))
        return ret

Leave a comment