class UserSerializer(ModelSerializer): password = fields.Str(load_only=True, required=False) company_id = fields.Str(required=False) class Meta: model = models.users fields = "__all__" dump_only = ("created_at", )
class CompanySerializer(ModelSerializer): id = fields.UUID() name = fields.Str() class Meta: model = db.company fields = '__all__'
def test_ma_fields_patched_required(): ma_fields = {key: value for key, value in vars(fields).items() if safe_issubclass(value, ma.fields.Field)} for key, value in ma_fields.items(): assert value._rf_patched # noqa if value is fields.Nested: # Nested field require to pass positional argument - Schema field_obj = value(ma.Schema()) elif value is fields.List: # List field required to pass positional argument - Field field_obj = value(fields.Str()) elif value is fields.Tuple: # Tuple field required to pass positional argument - tuple field_obj = value(tuple()) elif value is fields.Constant: # Tuple field required to pass positional argument - constant field_obj = value(1) elif value is fields.Pluck: # Pluck field required to pass two positional arguments - Schema and field_name field_obj = value(ma.Schema(), field_name="test") elif value is fields.Enum: # Pluck field required to pass two positional arguments - Schema and field_name field_obj = value(enum.Enum) else: field_obj = value() assert field_obj.required, ( f"`required` default True was not patched for {value.__name__} field" )
class UserSerializer(ModelSerializer): id = fields.UUID(read_only=True) password = fields.Str(write_only=True) created_at = fields.DateTime(read_only=True) class Meta: model = db.user fields = ('id', 'name', 'phone', 'email', 'password', 'created_at') @post_load def hash_password(self, data, **_): if 'password' in data: return {**data, 'password': hash_password(data['password'])} return data
class Ser(ModelSerializer): custom = fields.Str() class Meta: model = models.users fields = "__all__"
class BaseSerializer(Serializer): field_one = fields.Int() fields_two = fields.Str()
class UserWithFieldsALLSerializer(ModelSerializer): company_id = fields.Str(required=False) class Meta: model = models.users fields = "__all__"
class ReadWriteOnlyFieldsSerializer(Serializer): write = fields.Str(write_only=True) read = fields.Interval(read_only=True)