Comments (4)
No, this currently isn't supported, though I'm not opposed to adding it.
from djangorestframework-dataclasses.
Docstrings on dataclasses' fields are tricky to read, I'm told.
I managed to get away with adding a 'description'
to field()
's metadata and some plumbing in create_field()
.
@dataclass
class PublisherDto:
"""
A Publisher
"""
slug: str = field(metadata={
"description": "Some slug",
# "serializer_kwargs": { # this works, but it's verbose
# "help_text": "Some slug",
# },
})
class DtoSerializer(DataclassSerializer):
def create_field(self, field_name: str, extra_kwargs: KWArgs) -> SerializerField:
# Get the source field (this can be useful to represent a single dataclass field in multiple ways in the
# serialization state).
source = extra_kwargs.get('source', '*')
if source == '*':
source = field_name
# Determine the serializer field class and keyword arguments.
if source in self.dataclass_definition.fields:
field = self.dataclass_definition.fields[source]
# HERE ############################
if 'description' in field.metadata:
extra_kwargs = {'help_text': field.metadata['description'], **extra_kwargs}
###################################
if 'serializer_kwargs' in field.metadata: # merge extra kwargs defined in the field metadata
extra_kwargs = {**field.metadata['serializer_kwargs'], **extra_kwargs}
type_info = field_utils.get_type_info(self.dataclass_definition.field_types[source])
field_class, field_kwargs = self.build_typed_field(source, type_info, extra_kwargs)
elif hasattr(self.dataclass_definition.dataclass_type, source):
field_class, field_kwargs = self.build_property_field(source)
else:
field_class, field_kwargs = self.build_unknown_field(source)
# Include any extra kwargs defined through `Meta.extra_kwargs`
field_kwargs = self.include_extra_kwargs(field_kwargs, extra_kwargs)
# Create the serializer field instance.
return field_class(**field_kwargs)
from djangorestframework-dataclasses.
You can also override the init to pipe the docstring of the dataclass itself :
class DtoSerializer(DataclassSerializer):
def __init__(self, *args: Any, **kwargs: Any):
"""
Grab the class docstring from the dataclass and set it in the serializer,
so that the schema generator finds its and uses it.
"""
super(DtoSerializer, self).__init__(*args, **kwargs)
if self.dataclass_definition is not None:
type(self).__doc__ = self.dataclass_definition.dataclass_type.__doc__
from djangorestframework-dataclasses.
This library is super cool but it was not able to meet my needs with ergonomic support for help_text. Easier for me to just manually write out the serializers instead using serializers.Serializer (than use any of the above workarounds for example). The use case is to ensure that the OpenAPI schema generated with drf-spectacular have field descriptions. Thanks all
from djangorestframework-dataclasses.
Related Issues (20)
- TYPE_CHECKING imports result in error on type evaluation HOT 8
- Nesting dataclass serializer inside regular serializer can result in <class 'rest_framework.fields.empty'> for optional fields HOT 3
- "Invalid data. Expected a dictionary, but got <dataclass.type>" HOT 2
- bool field with default of True actually defaults to False when using QueryDict HOT 4
- Support union types and maybe other corner cases HOT 3
- Adding support for dataclass Union field HOT 8
- Mypy error: Type argument "X" of "DataclassSerializer" must be a subtype of "Dataclass" HOT 3
- Bug with @swagger_auto_schema in drf-yasg HOT 1
- Support for types like frozenset? HOT 8
- Serializer initializing dataclass with non init fields
- Why lock on dataclass?
- DataclassListSerializer can't deserialize objects HOT 2
- DataclassSerializer fails with `source="*"` embedded serialiser fields because it requires Meta.dataclass HOT 7
- Implement strict de-serialization option HOT 3
- Version 1.3.0 wheel package is missing `py.typed` file HOT 2
- PEP 695 type alias support
- `django-stubs` breaks type checking of `DataclassSerializer.validated_data` HOT 6
- [Feature request] Use `typing.Annotated` to redefine field types HOT 4
- Use 'source' to determine which fields should be autogenerated HOT 2
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 djangorestframework-dataclasses.