I will show two different validations, one with the validation of one attribute of the serializer and the second with the validation of different attributes.
  
  
  validation of different attributes in validate():
# serializers.py
class ProjectCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = [
            "id",
            "name",
            "description",
            "project_type",
        ]
    def validate(self, attrs):
        if (
            self.context["view"]
            .project.filter(name=attrs["name"], project_type=attrs["project_type"])
            .exists()
        ):
            raise serializers.ValidationError("Attention! This project exists already.")
        return attrs
self.context["view"].project this project property/attribute is created in view (ProjectViewSet). With this syntax we can get the project property and filter for existing projects. If this combination of name and project_type is found, the ValidationError will be raised. Otherwise the project will be validated.
  
  
  validation with one attributes in validate_user():
validate_user the user part is the name of the attribute from the serializer. If you have an attribute project the function name would be validate_project().
# serializers.py
class ContributorSerializer(serializers.ModelSerializer):
    # create attribute 'user', which is write_only because we just need to give a value
    user = serializers.IntegerField(write_only=True)
    class Meta:
        model = UserModel
        fields = ["id", "user"]
    def validate_user(self, value):
        user = UserModel.objects.filter(pk=value).first()
        if user is None:
            raise serializers.ValidationError("User does not exists!")
        if user.is_superuser:
            raise serializers.ValidationError(
                "Superusers cannot be added as contributors."
            )
        if self.context["view"].project.contributors.filter(pk=value).exists():
            raise serializers.ValidationError(
                "This user is already a contributor of this project."
            )
        return user
 

 
    
Top comments (0)