编辑我只想在我这样做时引发异常BrokerSerializer(user).data并且任何值是None我使用 DRF 来序列化对象以通过 API 导出它们,我不使用它来创建对象。在序列化模型时寻找一种最简单的方法来使字段成为必需的。API 需要一些字段不为空,所以我想提高APIMissingDataException它们中的任何一个是否为空/无。我试过:class BrokerSerializer(serializers.ModelSerializer): import_id = serializers.IntegerField(source='pk') deleted = serializers.SerializerMethodField() full_name = serializers.CharField(source='userprofile.get_display_name') phone_work = serializers.CharField(source='userprofile.contact_information.telephone') email_work = serializers.CharField(source='userprofile.contact_information.email')class Meta: model = User fields = ['import_id', 'deleted', 'full_name', 'phone_work', 'email_work'] required_fields = fieldsdef validate(self, attrs): super().validate(attrs) if not all([attrs.get(fieldname) for fieldname in self.Meta.required_fields]): raise APIMissingDataException() return attrsdef get_deleted(self, obj): return 0但是validate由于某种原因没有调用函数。我不想明确定义所有字段只是为了required=False向它们添加参数。In [10]: b = BrokerSerializer(User.objects.first()) In [11]: b.data # It should have raised exception since there are NoneOut[11]: {'import_id': 1, 'deleted': 0, 'full_name': None, 'phone_work': None, 'email_work': None}In [12]: b = BrokerSerializer(data=User.objects.first()) In [13]: b.is_valid() Out[13]: False有没有更舒服的方法?
添加回答
举报
0/150
提交
取消