Created
June 1, 2015 17:03
-
-
Save manuelzs/3906735feb1d8f4a5ab6 to your computer and use it in GitHub Desktop.
Tastypie CommaSeparatedIntegerField
This file contains hidden or 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 tastypie.fields import CharField | |
from tastypie.exceptions import ApiFieldError | |
class CommaSeparatedIntegerField(CharField): | |
""" | |
Converts django's string field to and from a list | |
""" | |
def dehydrate(self, bundle, for_list=True): | |
value = getattr(bundle.obj, self.attribute, None) | |
if value is not None: | |
try: | |
return [int(pk) for pk in value.split(',')] | |
except ValueError: | |
# If a value can't be converted to int the field will | |
# return null | |
return None | |
def hydrate(self, bundle): | |
if self.instance_name not in bundle.data: | |
return None | |
value = bundle.data[self.instance_name] | |
if value is None or len(value) == 0: | |
return None | |
value = str(value).lstrip('[').rstrip(']') | |
try: | |
[int(pk) for pk in value.split(',')] | |
return value | |
except ValueError: | |
raise ApiFieldError('The field %s must be an int array or null' | |
% (self.instance_name)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment