Skip to content

Instantly share code, notes, and snippets.

@jpadilla
Created February 3, 2014 21:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jpadilla/8792723 to your computer and use it in GitHub Desktop.
Save jpadilla/8792723 to your computer and use it in GitHub Desktop.
CharacterSeparatedField - A Django REST framework field that separates a string with a given separator into a native list and reverts a list into a string separated with a given separator.
from rest_framework import serializers
class CharacterSeparatedField(serializers.WritableField):
"""
A field that separates a string with a given separator into
a native list and reverts a list into a string separated with a given
separator.
"""
def __init__(self, *args, **kwargs):
self.separator = kwargs.pop('separator', ',')
super(CharacterSeparatedField, self).__init__(*args, **kwargs)
def to_native(self, obj):
if obj:
return self.separator.join(obj)
def from_native(self, data):
return data.split(self.separator)
def run_validators(self, value):
for val in value:
super(CharacterSeparatedField, self).run_validators(val)
from django.test import TestCase
from .fields import CharacterSeparatedField
class CharacterSeparatedFieldTestCase(TestCase):
def test_field_default_separator_is_comma(self):
"""
Tests that field should have a default comma separator specified.
"""
field = CharacterSeparatedField()
self.assertEqual(field.separator, ',')
def test_field_should_accept_custom_separator(self):
"""
Tests that field should accept a custom separator.
"""
field = CharacterSeparatedField(separator='.')
self.assertEqual(field.separator, '.')
def test_field_to_native_should_return_str_for_given_list(self):
"""
Tests that field's to_native method should return a string
from a specified list.
"""
field = CharacterSeparatedField()
self.assertEqual(field.to_native(['a', 'b', 'c']), 'a,b,c')
def test_field_from_native_should_return_list_for_given_str(self):
"""
Tests that field's from_native method should return a list
from a specified string.
"""
field = CharacterSeparatedField()
self.assertEqual(field.from_native('a,b,c'), ['a', 'b', 'c'])
@tomchristie
Copy link

Useful! Fancy a pull request linking to this from the REST framework docs? :)

@imomaliev
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment