Django Rest框架忽略自定义字段
发布时间:2022-05-09 19:57:17 214
相关标签:
我有一个带有可空布尔字段的模型,我希望以转换的方式序列化该字段null
在输出到false
.
我的模型:
class UserPreferences(models.Model):
receive_push_notifications = models.BooleanField(
null=True, blank=True,
help_text=("Receive push notifications))
我正在尝试使用这样一个自定义字段:
class StrictlyBooleanField(serializers.Field):
def to_representation(self, value):
# Force None to False
return bool(value)
def to_internal_value(self, data):
return bool(data)
class UserPreferencesSerializer(serializers.ModelSerializer):
class Meta(object):
model = UserPreferences
fields = ('receive_push_notifications',)
receive_push_notifications = StrictlyBooleanField()
但这不管用,我还在看null
在我的API回复中。
我想我一定是错过了一些简单的接线方式,因为如果我更换了我的电脑,我甚至都不会出错to_representation
与:
def to_representation(self, value):
raise
DRF似乎根本没有调用我的方法....我错过了什么?
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报