我有一个带有布尔字段的模型,我想用 Django 休息框架反序列化,我希望序列化程序在发布请求中缺少字段时抱怨。然而,事实并非如此。它默默地将缺少的布尔值解释为 False。
class UserProfile(models.Model):
"""
Message between two users
"""
user = models.OneToOneField(User, verbose_name="django authentication user", related_name='user_profile')
newsletter = models.BooleanField(null=False)
research = models.BooleanField(null=False)
该模型是使用这样的序列化器创建的:
class UserProfileSerializer(serializers.ModelSerializer):
research = BooleanField(source='research', required=True)
newsletter = BooleanField(source='newsletter', required=True)
class Meta:
model = UserProfile
fields = ('research', 'newsletter')
在我看来,我也在创建一个用户,所以我有一些手动步骤:
def post(self, request, format=None):
userprofile_serializer = UserProfileSerializer(data=request.DATA)
reg_serializer = RegistrationSerializer(data=request.DATA)
phone_serializer = PhoneSerializer(data=request.DATA)
errors = {}
if userprofile_serializer.is_valid() and reg_serializer.is_valid() and phone_serializer.is_valid():
user = reg_serializer.save()
data = reg_serializer.data
user_profile = userprofile_serializer.object
user_profile.user = user
userprofile_serializer.save()
return Response(data, status=status.HTTP_201_CREATED)
errors.update(reg_serializer.errors)
# ...
return Response(errors, status=status.HTTP_400_BAD_REQUEST)
但是,下面的测试用例失败了,因为其余框架没有抱怨缺少参数,而是在 from_native 中插入了一个 False
def test_error_missing_flag(self):
data = {'username': "test", 'password': "123test", 'email': 'test@me.com',
'newsletter': 'true', 'uuid': self.uuid}
response = self.client.post(reverse('app_register'), data)
# should complain that 'research' is not found
self.assertTrue('research' in response.data)
如果我将我的“研究”字段替换为序列化程序按预期失败的整数字段。有任何想法吗?