File: custom_validators.py

package info (click to toggle)
python-odmantic 1.0.2-4
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,640 kB
  • sloc: python: 8,547; sh: 37; makefile: 34; xml: 13; javascript: 3
file content (61 lines) | stat: -rw-r--r-- 1,469 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from typing import ClassVar

from pydantic import ValidationError, model_validator

from odmantic import Model


class SmallRectangle(Model):
    MAX_AREA: ClassVar[float] = 9

    length: float
    width: float

    @model_validator(mode="before")
    def check_width_length(cls, values):
        length = values.get("length", 0)
        width = values.get("width", 0)
        if width > length:
            raise ValueError("width can't be greater than length")
        return values

    @model_validator(mode="before")
    def check_area(cls, values):
        length = values.get("length", 0)
        width = values.get("width", 0)
        if length * width > cls.MAX_AREA:
            raise ValueError(f"area is greater than {cls.MAX_AREA}")
        return values


print(SmallRectangle(length=2, width=1))
# > id=ObjectId('5f81e3c073103f509f97e374'), length=2.0, width=1.0

try:
    SmallRectangle(length=2)
except ValidationError as e:
    print(e)
    """
    1 validation error for SmallRectangle
    width
      field required (type=value_error.missing)
    """

try:
    SmallRectangle(length=2, width=3)
except ValidationError as e:
    print(e)
    """
    1 validation error for SmallRectangle
      Value error, width can't be greater than length
    """

try:
    SmallRectangle(length=4, width=3)
except ValidationError as e:
    print(e)
    """
    1 validation error for SmallRectangle
    __root__
      Value error, area is greater than 9
    """