5

I used the code below: It shows duplicated validator. Why cannot use both? How do I create an alias in the @validator if I cannot use Field?

from pydantic import BaseModel, validator, Field
import datetime

class MultiSourceInput(BaseModel):
    abc :   str = Field(..., alias= 'abc_1',description= "xxxxxxxxxxxx.")
    xyz :   int= Field(..., description= "xxxxxxxx ",ge=0, le=150)

    @validator("abc")
    def abc(value): 
        values = float(value) 
        if value <=141 and value>=0: 
            return value
        else:
            0

Here's the traceback:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 37, in MultiSourceInput
  File "pydantic/class_validators.py", line 85, in pydantic.class_validators.validator.dec
  File "pydantic/class_validators.py", line 144, in pydantic.class_validators._prepare_validator
pydantic.errors.ConfigError: duplicate validator function "__main__.MultiSourceInput.abc"; if this is intended, set `allow_reuse=True`
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
slashie
  • 127
  • 1
  • 10

3 Answers3

5

In my case, this occurred because the validation method was receiving self instead of cls, meaning:

    @validator("my_field")
    def parse_my_field(self, v):
        ...

Instead of:

    @validator("my_field")
    def parse_my_field(cls, v):
        ...
A. Kali
  • 739
  • 6
  • 19
2

My issue was caused by errors (seemingly unrelated) earlier in the code. Some knock-on effects caused the duplicate validator function error. When I fixed the preceding errors this went away

Joshua Patterson
  • 439
  • 5
  • 12
0

Check if there is a validator created with abc method name. You might need to rename the method