在Django Rest Framework中创建BooleanField

我有一个带有布尔字段的模型,我想用Django休息框架反序列化,我希望序列化器在post请求中缺少字段时进行抱怨.然而,它没有.它默默地将缺少的布尔值解释为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)

使用如下的Serialiser创建模型:

 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)

如果我用“整数”字段替换“研究”字段,则序列化程序会按预期失败.有任何想法吗?

最佳答案 布尔字段和必需参数存在问题.现在应该在master中修复.

请参阅此问题:https://github.com/tomchristie/django-rest-framework/issues/1004

点赞