Created
February 3, 2014 21:24
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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']) |
@jpadilla @tomchristie here is my take on this https://gist.github.com/imomaliev/77fdfd0ab5f1b324f4e496768534737e
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Useful! Fancy a pull request linking to this from the REST framework docs? :)