with python and marshmallow how i can validate a field with a parent field

37 views Asked by At

i am trying to validate one field with another one that is on the top of the structure, but when i try @validates_schema the data is just from the current level, so i can only validate one field vs another if they are in the same level, how can i validate vs another field anywhere in the data structure?

my ideas. i tought passing the dictionary into the class as init, but not sure how with the Schema class

from marshmallow import Schema, fields, validates_schema, ValidationError



class project_schema(Schema):
    field1 = fields.Integer()
    field2 = fields.Integer()

class parameters_schema(Schema):
    parm1 = fields.Integer()
    parm2 = fields.Integer()

    @validates_schema  # validates the schema form this field down, not ALL the DICTIONARY
    def validate_performance(self, data, **kwargs):
        print(data)
        # todo how can i get the WHOLE dictionary structure from the root so i can say
        # if this fields exists or its value is xyz
        # then want_to_check_if_this_exists
        # raise ValidationError("if parm1 is 1 want_to_check_if_this_exists most be false")


# root
class root_schema(Schema):
    project = fields.Nested(project_schema)
    parameters = fields.Nested(parameters_schema)
    want_to_check_if_this_exists = fields.Boolean()


dict = {"project": {
    "field1": 1,
    "field2": 2
    },
    "parameters": {
        "parm1": 1,
        "parm2": 2
    },
    "want_to_check_if_this_exists": True
}


try:
    result = root_schema().load(dict)
except ValidationError as err:
    print(err.messages)
    # print(err.valid_data)

what i ended up doing in a very ugly way:

  1. before result = root_schema().load(dict) i pickle the dictionary into a file.
  2. put the path of that pickle file into a environment variable.
  3. when i did the validation function.
  4. i pickle.load the file to get the dictionary back into memory.
  5. now i can do depicle_file["want_to_check_if_this_exists"] and make the validations that i want.

but this is very very ugly and depends on creating a file =(.

any ideas on how to achive validating vs other fields along the data structure?

thanks guys

0

There are 0 answers