Package: drf-turbo
drf-turboOverviewdrf-turbo is a drop-in serializer for Django REST Framework (DRF). drf-turbo serializers run around 7.75 times faster
than what what you get from DRF’s packaged serializer.RequirementsDjangoDjango REST Frameworkpytzforbiddenfruitpyyaml(OpenAPI)uritemplate(OpenAPI)djangorestframework-simplejwt(OpenAPI)Installation$pipinstalldrf-turboTo install Cython on MacOSvia Brew:$brewinstallcythonPerformancedrf-turboserialization, deserialization and validation performance averages 86% faster than DRF’s standard serializer.For more details, visit thebenchmarks sectionof the docs.Documentation & SupportDocumentation for the project is available athttps://drf-turbo.readthedocs.io.For questions and support, use github issuesExamplesDeclaring Serializersfromdatetimeimportdatetimefromdjango.utils.timezoneimportnowimportdrf_turboasdtclassUser:def__init__(self,username,email,created=None):self.username=usernameself.email=emailself.created=createdordatetime.now()user=User(username='test',email='test@example.com')classUserSerializer(dt.Serializer):username=dt.StrField(max_length=50)email=dt.EmailField()created=dt.DateTimeField()Serializing objectsserializer=UserSerializer(user)serializer.data# {'username': 'test', 'email': 'test@example.com', 'created': '2021-11-04T22:49:01.981127Z'}Deserializing objectsdata={'username':'new_test','email':'test2@example.com','created':now()}serializer=UserSerializer(data=data)serializer.is_valid()# Trueserializer.validated_data# {'username': 'new_test', 'email': 'test2@example.com', 'created': datetime.datetime(2021, 11, 12, 6, 10, 44, 85118)}}Validationserializer=UserSerializer(data={'email':'test'})serializer.is_valid()# Falseserializer.errors# {'username': ['This field is required.'], 'email': ['Enter a valid email address.'],'created': ['This field is required.']}Field-level validationimportdrf_turboasdtclassUserSerializer(dt.Serializer):username=dt.StrField(max_length=50)defvalidate_username(self,value):if'test'notinvalue.lower():raisedt.ValidationError("test must be in username")returnvalueObject-level validationimportdrf_turboasdtclassCampaignSerializer(dt.Serializer):start_date=dt.DateTimeField()end_date=dt.DateTimeField()defvalidate(self,data):ifdata['start_date']>data['end_date']:raisedt.ValidationError("start_date must occur before end_date")returndataNested Serializersfromdatetimeimportdatetimefromdjango.utils.timezoneimportnowimportdrf_turboasdtclassUser:def__init__(self,username,email,created=None):self.username=usernameself.email=emailself.created=createdordatetime.now()user=User(username='test',email='test@example.com')classUserSerializer(dt.Serializer):username=dt.StrField(max_length=50)email=dt.EmailField()created=dt.DateTimeField()classProfile:def__init__(self,age=25):self.age=ageself.user=userprofile=Profile()classProfileSerializer(dt.Serializer):age=dt.IntField()user=UserSerializer()serializer=ProfileSerializer(profile)serializer.data# {'age' : 25 , 'user' : {'username': 'test', 'email': 'test@example.com', 'created': '2021-11-04T22:49:01.981127Z'}}Filtering Outputdrf-turbo provides option to enclude or exclude fields from serializer usingonlyorexcludekeywords.serializer=UserSerializer(user,only=('id','username'))orserializer=ProfileSerializer(profile,exclude=('id','user__email'))orhttp://127.0.0.1:8000/user/?only=id,usernameRequired FieldsMake a field required by passing required=True. An error will be raised if the the value is missing from data during Deserializing.For example:classUserSerializer(dt.Serializer):username=dt.StrField(required=True,error_messages={"required":"no username"})Specifying DefaultsIt will be used for the field if no input value is supplied.For example:fromdatetimeimportdatetimeclassUserSerializer(dt.Serializer):birthdate=dt.DateTimeField(default=datetime(2021,11,05))ModelSerializerMapping serializer to Django model definitions.Features :It will automatically generate a set of fields for you, based on the model.It will automatically generate validators for the serializer.It includes simple default implementations of .create() and .update().classUserSerializer(dt.ModelSerializer):classMeta:model=Userfields=('id','username','email')You can also set the fields attribute to the special value__all__to indicate that all fields in the model should be used.For example:classUserSerializer(dt.ModelSerializer):classMeta:model=Userfields='__all__'You can set the exclude attribute to a list of fields to be excluded from the serializer.For example:classUserSerializer(dt.ModelSerializer):classMeta:model=Userexclude=('email',)Read&Write only fieldsclassUserSerializer(dt.ModelSerializer):classMeta:model=Userfields=('id','username','password','password_confirmation')read_only_fields=('username')write_only_fields=('password','password_confirmation')OpenApi(Swagger)Add drf-turbo to installed apps insettings.pyINSTALLED_APPS=[# ALL YOUR APPS'drf_turbo',]and then register our openapi AutoSchema with DRF.REST_FRAMEWORK={# YOUR SETTINGS'DEFAULT_SCHEMA_CLASS':'drf_turbo.openapi.AutoSchema',}and finally add these lines inurls.pyfromdjango.views.genericimportTemplateViewfromrest_framework.schemasimportget_schema_viewasschema_viewfromdrf_turbo.openapiimportSchemaGeneratorurlpatterns=[# YOUR PATTERNSpath('openapi',schema_view(title="Your Project",description="API for all things …",version="1.0.0",generator_class=SchemaGenerator,public=True,),name='openapi-schema'),path('docs/',TemplateView.as_view(template_name='docs.html',extra_context={'schema_url':'openapi-schema'}),name='swagger-ui'),]Now go tohttp://127.0.0.1:8000/docsCreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.LicenseFree software: MIT licenseHistory0.1.0 (2021-11-10)First release on PyPI.0.1.2 (2021-11-11)performance improvments0.1.3 (2021-11-12)fix override error messages0.1.5 (2021-11-21)fix get_attribute on related field issue0.1.6 (2022-05-29)clean projectdrop support for renderers,parsers, and responsesremove deprecated methods0.1.7 (2023-08-19)pin requirementsuse c extensions0.1.8 (2023-10-11)add support for django 4.00.1.9 (2023-10-11)add support for python 3.10