Coverage for src/backend/InvenTree/data_exporter/serializers.py: 22%

35 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-07 17:47 +0000

1"""Serializers for the exporter app.""" 

2 

3from django.utils.translation import gettext_lazy as _ 

4 

5from rest_framework import serializers 

6 

7import InvenTree.exceptions 

8import InvenTree.helpers 

9from plugin import PluginMixinEnum, registry 

10 

11 

12class DataExportOptionsSerializer(serializers.Serializer): 

13 """Serializer class for defining a data export session.""" 

14 

15 class Meta: 

16 """Metaclass options for this serializer.""" 

17 

18 fields = ['export_format', 'export_plugin'] 

19 

20 def __init__(self, *args, **kwargs): 

21 """Construct the DataExportOptionsSerializer. 

22 

23 - The exact nature of the available fields depends on which plugin is selected. 

24 - The selected plugin may 'extend' the fields available in the serializer. 

25 """ 

26 # Reset fields to a known state 

27 self.Meta.fields = ['export_format', 'export_plugin'] 

28 

29 # Generate a list of plugins to choose from 

30 # If a model type is provided, use this to filter the list of plugins 

31 serializer_class = kwargs.pop('serializer_class', None) 

32 model_class = kwargs.pop('model_class', None) 

33 view_class = kwargs.pop('view_class', None) 

34 

35 request = kwargs.pop('request', None) 

36 

37 # Is a plugin serializer provided? 

38 if plugin := kwargs.pop('plugin', None): 

39 if hasattr(plugin, 'get_export_options_serializer'): 

40 plugin_serializer = plugin.get_export_options_serializer() 

41 

42 if plugin_serializer: 

43 for key, field in plugin_serializer.fields.items(): 

44 # Note: Custom fields *must* start with 'export_' prefix 

45 if key.startswith('export_') and key not in self.Meta.fields: 

46 self.Meta.fields.append(key) 

47 setattr(self, key, field) 

48 

49 plugin_options = [] 

50 

51 for plugin in registry.with_mixin(PluginMixinEnum.EXPORTER): 

52 try: 

53 supports_export = plugin.supports_export( 

54 model_class, 

55 user=request.user if request else None, 

56 serializer_class=serializer_class, 

57 view_class=view_class, 

58 ) 

59 except Exception: 

60 InvenTree.exceptions.log_error('supports_export', plugin=plugin.slug) 

61 supports_export = False 

62 

63 if supports_export: 

64 plugin_options.append((plugin.slug, plugin.name)) 

65 

66 self.fields['export_plugin'].choices = plugin_options 

67 

68 super().__init__(*args, **kwargs) 

69 

70 export_format = serializers.ChoiceField( 

71 choices=InvenTree.helpers.GetExportOptions(), 

72 default='csv', 

73 label=_('Export Format'), 

74 help_text=_('Select export file format'), 

75 ) 

76 

77 # Select plugin for export - the options will be dynamically generated later on 

78 export_plugin = serializers.ChoiceField( 

79 choices=[], 

80 default='inventree-exporter', 

81 label=_('Export Plugin'), 

82 help_text=_('Select export plugin'), 

83 )