You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have created my own custom command, and figured it could be of use to other people it currently goes through each installed app checks for serializers and will automatically apply the @ts_interafce decorator to them:
importimportlibimportinspectimportosfromtypesimportModuleTypefromdjango.appsimportAppConfigfromdjango.confimportsettingsfromdjango.core.management.baseimportBaseCommandfromdjango_typomaticimportts_interface, get_tsfromrest_framework.serializersimportSerializerclassCommand(BaseCommand):
EXCLUDED_APPS= ['rest_framework']
help='Creates a TypeScript definition file for all models registered in DRF serializers under src/ts/@types/django-models.d.ts'defcreate_model_mappings(self, app_config: AppConfig):
"""Updates the custom mappings with related models and their type in ts"""mappings= {}
formodelinapp_config.get_models():
forfieldinmodel._meta.get_fields():
iffield.related_modelisnotNone:
ts_type=field.related_model.__name__iffield.many_to_manyorfield.one_to_many:
ts_type+='[]'mappings[field.name] =ts_typereturnmappingsdefhandle(self, *args, **options):
fromdjango.appsimportappsforapp_configinapps.get_app_configs():
ifapp_config.namenotinself.EXCLUDED_APPS:
self.handle_app_config(app_config)
# Remove Serializer from type name since it's redundant in TSts=get_ts().replace('Serializer', '')
type_file_location=os.path.join(settings.BASE_DIR, 'src/ts/@types/django-models.d.ts')
withopen(type_file_location, 'w') astype_file:
type_file.write(ts)
self.stdout.write(self.style.SUCCESS(f'Type file sucessfully generated at {type_file_location}'))
defhandle_app_config(self, app_config: AppConfig):
try: #Check to see the app has serializersserializers_module: ModuleType=importlib.import_module(app_config.name+'.serializers')
exceptImportError:
returnmappings=self.create_model_mappings(app_config)
serializers=inspect.getmembers(serializers_module, lambdamember: self.is_serializer(member, serializers_module))
forname, serializerinserializers:
# Get the class def and apply the ts_interface decorator to itbase_class=getattr(serializers_module, name)
ts_interface(mapping_overrides=mappings)(base_class)
defis_serializer(self, member: object, module):
"""Checks to see if the given member is a serializer class and is a part of the given module"""returninspect.isclass(member) andissubclass(member, Serializer) andmember.__module__==module.__name__
The text was updated successfully, but these errors were encountered:
I have created my own custom command, and figured it could be of use to other people it currently goes through each installed app checks for serializers and will automatically apply the @ts_interafce decorator to them:
The text was updated successfully, but these errors were encountered: