Comments (12)
I could work around it by using drf-enum-field:
from drf_enum_field.serializers import EnumFieldSerializerMixin
class VehicleSerializer(EnumFieldSerializerMixin, serializers.ModelSerializer):
...
from django-enumfields.
I use a custom DRF field for this:
models.py
from enum import Enum
from django.db import models
from enumfields import EnumIntegerField
class GeoModel(models.Model):
class LocationType(Enum):
ROOFTOP = 1
RANGE_INTERPOLATED = 2
GEOMETRIC_CENTER = 3
APPROXIMATE = 4
UNRESOLVED = 5
location_type = EnumIntegerField(
enum=LocationType,
default=LocationType.UNRESOLVED
)
...
fields.py
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
def __init__(self, enum, **kwargs):
self.enum = enum
kwargs['choices'] = [(e.name, e.name) for e in enum]
super(EnumField, self).__init__(**kwargs)
def to_representation(self, obj):
return obj.name
def to_internal_value(self, data):
try:
return self.enum[data]
except KeyError:
self.fail('invalid_choice', input=data)
serializers.py
from rest_framework import serializers
from . import fields
from . import models
class GeoModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.GeoModel
location_type = fields.EnumField(enum=models.GeoModel.LocationType)
from django-enumfields.
DRF serializers referring to models with EnumField
s should either
- use
enumfields.drf.fields.EnumField
serializer fields for enum model fields, or - add the
EnumSupportSerializerMixin
that teachesModelSerializer
s to use the above serializer field forEnumField
s.
That should fix these issues. Feel free to comment and/or open a new issue if I missed something here! 😄
from django-enumfields.
Hm, we're using this with DRF but Python 2.7. Do you think you could put together a small test for this? It shouldn't need DRF—my guess is that just trying to serialize the model will trigger it. All the tests are being run in 3.4 with tox so that would make it really easy for us to dive in. Either way, thanks for the report!
from django-enumfields.
I added pull request #31
I'm a bit mystified you don't see an error on python 2.7. Perhaps it somehow avoids this path entirely.
from django-enumfields.
I tried running my project on python 2.7 and I still see the serializer error. Perhaps there is something wrong with my definitions?
Here are my models: https://github.com/jessamynsmith/eggtimer/blob/master/periods/models.py#L74
and serializers: https://github.com/jessamynsmith/eggtimer/blob/django_enumfields/periods/serializers.py
Also, here is the test that works on master, with django-enumfield:
https://github.com/jessamynsmith/eggtimer/blob/master/periods/tests/test_serializers.py
and errors out on the branch, with django-enumfields:
https://github.com/jessamynsmith/eggtimer/blob/django_enumfields/periods/tests/test_serializers.py
from django-enumfields.
Sorry to necro an issue.
I just wrote a DRF serializer field, then looked here to see that @hacknaked wrote almost exactly the same thing.
Proposal: add that code to this project and make DRF automagically use it. Something along the lines of:
def _make_drf_enum_field():
import enumfields
from distutils.version import StrictVersion
try:
import rest_framework
except ImportError:
return # DRF not installed
if StrictVersion(rest_framework.__version__) < StrictVersion('3.0'):
return # DRF version too old
class EnumField:
(the code above)
# Patch DRF
rest_framework.serializers.ModelSerializer.serializer_field_mapping[enumfields.EnumField] = EnumField
rest_framework.serializers.ModelSerializer.serializer_field_mapping[enumfields.EnumIntegerField] = EnumField
return EnumField
EnumField = _make_drf_enum_field()
if EnumField is None:
del EnumField
cc: @tomchristie -- Is there a supported way of registering new mappings like this?
from django-enumfields.
There's no automagical way for custom fields to declare how they should be mapped to serializer fields, no. (Out of interest what serializer field does it create? print a ModelSerializer to find out). It's not impossible that we could think about adding an API for this if we knew it was going to get uptake from third party modelfield implementations.
from django-enumfields.
Thanks for the quick response, Tom! They create ChoiceFields.
from django-enumfields.
@aelavender I have tried the solution hereabove yet there are issue serializing the field due to line https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L1214 that override the field_class
got from rest_framework.serializers.ModelSerializer.serializer_field_mapping
.
Is it critical for enumfields to have the field with the choices named choices
? or can we rename this field to choices_enum
to avoid triggering line https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L1211 ?
from django-enumfields.
I can make it working by replacing the line https://github.com/hzdg/django-enumfields/blob/master/enumfields/fields.py#L43 to
(i.value, getattr(i, 'label', i.name))
without needing the code above but adding to my Enum type:
def __str__(self):
return self.value
from django-enumfields.
We just ran into this bug/omission, drf-yasg (our documentation generator) is crashing because of it.
A fix would be appreciated.
from django-enumfields.
Related Issues (20)
- Drop Python2 compatibility HOT 4
- Add blurb about included enumeration types in Django 3.0? HOT 4
- Automatically register EnumFieldListFilter
- faced this while trying to upgrade a django 1.8 project to django 2.2/3.0 HOT 8
- New release on PyPI HOT 2
- Customize enum choices in serializer HOT 2
- 2.1.0 Incompatibility with drf-yasg HOT 2
- DRF : Object of type Gender is not JSON serializable when calling OPTIONS request HOT 1
- Limit choices of an enum HOT 2
- Migrate to new CI platform HOT 5
- Python 3.11 Support HOT 1
- Allow to serialize enum by names HOT 2
- Breaks with django 2.0 HOT 4
- Calculate max_length automatically? HOT 2
- Deprecation warning in Django 2.1.1 HOT 2
- Support Field attributes (like 'name', etc) HOT 1
- Accept subset of the Enum values HOT 2
- Incompatibility with django-filter HOT 1
- Is the project alive? HOT 13
- Includes tests in source tarball
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from django-enumfields.