Skip to content

Commit

Permalink
bind compatibility to django-hstore >= 1.3.1
Browse files Browse the repository at this point in the history
  • Loading branch information
nemesifier committed Aug 26, 2014
1 parent 060c61b commit 73e4b65
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 36 deletions.
45 changes: 10 additions & 35 deletions rest_framework_hstore/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,46 +18,16 @@ class HStoreSerializer(ModelSerializer):
to django-rest-framework
"""
def __init__(self, *args, **kwargs):
self.__map_virtual_fields()
self.contribute_to_field_mapping()
super(HStoreSerializer, self).__init__(*args, **kwargs)

def __map_virtual_fields(self):
def contribute_to_field_mapping(self):
"""
the standard DRF field_mapping uses model field classes as keys:
field_mapping = {
...
models.DateField: DateField,
...
}
we need to add strings with the name of the classes to the mapping:
field_mapping = {
...
models.DateField: DateField,
"models.DateField": DateField,
...
}
The reason is that a virtual field won't match the standard django field,
but can match the string version.
add DictionaryField to field_mapping
"""
# add DictionaryField to field_mapping
self.field_mapping[DictionaryField] = HStoreField
# TODO: support ReferenceField
self.field_mapping[DictionaryField] = HStoreField

additional_fields = {}
# iterate over self.field_mapping
for field_class, serializer_field in self.field_mapping.items():
# if the field can be represented as a string
if hasattr(field_class, '__name__'):
# add mapping using string instead of class
additional_fields[field_class.__name__] = serializer_field

# update field_mapping dictionary
self.field_mapping.update(additional_fields)

def get_field(self, model_field):
"""
Creates a default instance of a basic non-relational field.
Expand Down Expand Up @@ -112,9 +82,14 @@ def get_field(self, model_field):

if model_field.__class__ == DictionaryField and model_field.schema:
kwargs['schema'] = True

# === django-rest-framework-hstore specific ====
# if available, use __basefield__ attribute instead of __class__
# this will cause DRF to pick the correct DRF-field
key = getattr(model_field, '__basefield__', model_field.__class__)

try:
return self.field_mapping[model_field.__class__](**kwargs)
return self.field_mapping[key](**kwargs)
except KeyError:
pass

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
license = 'BSD'
install_requires = [
'djangorestframework',
'django_hstore'
'django_hstore>=1.3.1'
]
classifiers=[
'Development Status :: 3 - Alpha',
Expand Down

0 comments on commit 73e4b65

Please sign in to comment.