我有EmailCreateSerializer
,我可以让创作者通过receive_group
ID或receive_user
ID向他们发送电子邮件:
class EmailCreateSerializer(Serializer):
receive_group = serializers.IntegerField(allow_null=True)
receive_user = serializers.IntegerField(allow_null=True)
传递receive_group(发送到组)或receive_user(发送给单个用户)。
但是我希望有一个约束,它们(receive_group
,receive_user
)都不能为空。
有没有办法在Serializer类中执行此操作?
答案 0 :(得分:0)
您可以覆盖序列化程序的validate()
方法来检查:
class EmailCreateSerializer(Serializer):
receive_group = serializers.IntegerField(allow_null=True)
receive_user = serializers.IntegerField(allow_null=True)
def validate(self, data):
if data['receive_group'] is None and data['receive_user'] is None:
raise serializers.ValidationError("Group or User cannot be empty, pass information for at least one of those.")
return data
文档:http://www.django-rest-framework.org/api-guide/serializers/#object-level-validation