[Python] How to add a validation to a model serializer so that it ensures at least one of two...

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    EDIT: A bit more technical description follows.

    So, I have a model:

    class MyModel(UUIDModel):
    file = models.FileField(blank=True, null=True, ...)
    code = models.CharField(blank=True, null=True, ...)

    def clean(self):
    super().clean()
    if not self.file and not self.code:
    raise ValidationError("At least one of the fields 'file' or 'code' must be provided.")

    def save(self, *args, **kwargs):
    self.full_clean()
    super().save(*args, **kwargs)


    So, this is the model.

    Now, this addition here was enough to add this validation to the admin panel functionality for this.

    For the API part, I have a serializer:

    class MySerializer(serializers.ModelSerializer):
    file = serializers.FileField(required=False)
    code = serializers.CharField(required=False)

    class Meta:
    model = MyModel
    fields = ("file", "code")

    def validate(self, data):
    file = data.get('file')
    code = data.get('code')
    if not file and not code:
    raise serializers.ValidationError("At least one out of 'file' or 'code' must be provided.")
    return data


    So, this is the approach I'm going for but it doesn't work while hitting POST requests to the endpoint. Even if I don't pass any of these two fields, I still don't get an error.

    I wanna implement it such that if none of the fields is passed, it throws an error for both fields and even if one is passed, it doesn't and no error for both either.

    Any help will be appreciated. Thanks!

    EDIT: The errors do occur actually but once all the other required fields in the model are provided, only then. They don't appear with the whole list of validation errors.

    Continue reading...

Compartilhe esta Página