File: on_save_validation.md

package info (click to toggle)
python-beanie 1.29.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,544 kB
  • sloc: python: 14,413; makefile: 7; sh: 6
file content (28 lines) | stat: -rw-r--r-- 826 bytes parent folder | download
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
# On save validation

Pydantic has a very useful config to validate values on assignment - `validate_assignment = True`. 
But, unfortunately, this is an expensive operation and doesn't fit some use cases.
You can validate all the values before saving the document (`insert`, `replace`, `save`, `save_changes`) 
with beanie config `validate_on_save` instead.

This feature must be turned on in the `Settings` inner class explicitly:

```python
class Sample(Document):
    num: int
    name: str

    class Settings:
        validate_on_save = True
```

If any field has a wrong value, 
it will raise an error on write operations (`insert`, `replace`, `save`, `save_changes`).

```python
sample = Sample.find_one(Sample.name == "Test")
sample.num = "wrong value type"

# Next call will raise an error
await sample.replace()
```