Package: pydref-serializers
PyDReF - SerializersDescriptionThis library contains a set of tools to help you create simple serializers for Django models. It was inspired by theDjango REST FrameworkandPydanticprojects.MotivationThe main motivation for creating this library was to have a simple and easy to use tool to serialize Django models. The library is designed to be used in projects where you need to serialize Django models, but you don't want to use the Django REST Framework.DRF is a great tool, but it is not always necessary to use it. For example, if you need to create a simple API for a small project, you can use this library instead of the DRFfor the serialization of your models.Also, though DRF is a great tool, I've never enjoy the heavy responsibility added to its Serializers. Pydantic keeps this simplicity, where the serializers (Pydantic models) are just a simple class that you can use to serialize your data.InstallationYou can install this library using pip:pipinstallpydref-serializersUsageCreating a serializer classFor creating a serializer for a Django model, you can use theModelSerializerBuilderclass. This class will create a Pydantic model based on the Django model that you pass to it.frompydref_serializersimportModelSerializerBuilderfrommyapp.modelsimportMyModelMyModelSerializer=ModelSerializerBuilder.from_model_class(MyModel)The builder will return a class created based on the specified model. If you want to set the fields to be added to the serializer, you can specify them during the creation of the serializer, using the kwargsinclude_fieldsorexclude_fields:frompydref_serializersimportModelSerializerBuilderfrommyapp.modelsimportMyModelMyModelSerializer=ModelSerializerBuilder.from_model_class(MyModel,include_fields=['field1','field2','field3'],# exclude_fields=['field1', 'field2', 'field3'],)TheModelSerializerBuilderalso has a few kwargs for configuration how the builder get the fields from the Django model, and also how it maps the fields to the Pydantic model fields.frompydref_serializersimportModelSerializerBuilderfrommyapp.modelsimportMyModel_FieldMapper=Callable[[DjangoField],tuple[type,Any]]_FieldGetter=Callable[[type[DjangoModel],Collection[str]|None,Collection[str]|None],dict[type,Any]]MyModelSerializer=ModelSerializerBuilder.from_model_class(MyModel,...,# include_fields or exclude_fieldsfields_getter:_FieldGetter=...,field_mapper:_FieldMapper=...,)Using the serializerFor using the serializer, you can use it as a normal Pydantic model, passing the fields to be serialized as kwargs to the constructor:frommyapp.serializersimportMyModelSerializerserializer=MyModelSerializer(field1='value1',field2='value2',field3='value3',)The serializer will validate the fields based on the validators created during the Django Fields to Pydantic annotations mapping.You can also use the serializer to serialize a Django model instance:frommyapp.serializersimportMyModelSerializerfrommyapp.modelsimportMyModelmy_model_instance=MyModel.objects.get(pk=1)serializer=MyModelSerializer.from_model(my_model_instance)The class methodfrom_modelwill create a serializer instance based on the Django model instance passed to it. It will convert the model to dict using the django utilitymodel_to_dictlocated atdjango.forms.models, and then it will pass the dict to the serializer constructor. You can change this behavior passing a custom function to themodel_to_dictkwarg of thefrom_modelmethod:frommyapp.serializersimportMyModelSerializerfrommyapp.modelsimportMyModelmy_model_instance=MyModel.objects.get(pk=1)serializer=MyModelSerializer.from_model(my_model_instance,model_to_dict=lambdamodel_instance:model_instance.to_dict(),)Field mappingFields are transformed based on the following rules:Field types are mapped from Django Field to Pydantic annotations based on the dictionary below:DJANGO_FIELD_MAP={# Numerical related fields"AutoField":int,"BigAutoField":int,"IntegerField":int,"SmallIntegerField":int,"BigIntegerField":int,"PositiveIntegerField":PositiveInt,"PositiveSmallIntegerField":PositiveInt,"FloatField":float,"DecimalField":Decimal,# String related fields"CharField":str,"TextField":str,"SlugField":str,"EmailField":EmailStr,"URLField":AnyUrl,"FilePathField":FilePath,"FileField":FilePath,"ImageField":FilePath,# Other built-in fields"BooleanField":bool,"BinaryField":bytes,"DateField":date,"DateTimeField":datetime,"DurationField":timedelta,"TimeField":time,"UUIDField":UUID,"GenericIPAddressField":IPvAnyAddress,"JSONField":Json,}If Django fieldmax_lengthis set, the Pydantic field will also be set withmax_lengthequal to the Django fieldmax_length.If Django field hasblank=True, the Pydantic field will havemin_length=0.If Django field hasblank=False, the Pydantic field will havemin_length=1.If Django field hasnull=True, the Pydantic field will havefield_type | None.If Django field hasdefaultvalue set, the Pydantic field will havedefaultset to the Django fielddefault. In case this value is a callable, it will be used for the pydantic fielddefault_factory.If Django field haschoicesset, the Pydantic field will sue as a type an created Enum based on the specifiedchoicesset to the Django field. If the field is int based, the Enum will be an IntEnum. If the field is str based, the Enum will be StrEnum, otherwise it will be an Enum.TODOAdd support for lower Python versions (3.6+).Add support for Django model relations.Add support for Django model inheritance.Add support for Django model fields with custom validators.Add support to customize the serializer fields.Add support to serialize model properties.