Question:
How to set a default based on another field in pydantic BaseModel?

In Pydantic, you can set a default value for a field based on another field by defining a method that computes the default value and using the @validator decorator to apply it. Here's an example of how to do this:

from pydantic import BaseModel, validator

class MyModel(BaseModel):
 field1: int
 field2: int

>@validator(‘field2’, pre=True, always=True)
 def set_field2_default(cls, v, values):
 # You can access the value of field1 from the ‘values’ dictionary
 field1_value = values.get(‘field1’)
 
 # Calculate the default value for field2 based on field1
 default_value = field1_value * 2
 
 # Return the default value
 return default_value

# Creating an instance of MyModel
my_model = MyModel(field1=3)

# When you don’t specify field2, it will be computed based on field1
print(my_model.field2) # Output: 6

In the example above, we define a Pydantic model MyModel with two fields, field1 and field2. We use the @validator decorator to define a validation function set_field2_default for field2. This function takes two arguments: cls (the class itself) and values (a dictionary of the values of all fields in the model).

Inside the set_field2_default function, we calculate the default value for field2 based on the value of field1 (which we retrieve from the values dictionary). We then return this default value, which will be assigned to field2 when an instance of MyModel is created without specifying a value for field2.

This allows you to set a default value for one field based on the value of another field in a Pydantic BaseModel.

 

Solution:

I was able to acheive it using a root_validator:

class Wallet(BaseModel):
    address: str = None
    private_key: str = Field(default_factory=key.generate_private_key)

    @root_validator
    def get_address(cls, values) -> dict:
        if values.get("address") is None:
            values["address"] = key.generate_address(values.get("private_key"))
        return values
Answered By >KOB
Credit to >StackOverflow

More Questions:

>ChatGPT: Features, advantages & disadvantages-ChatGPT

>What is ChatGPT and How Does ChatGPT Work?-ChatGPT

>Python File Error: "Time Limit Exceeded" | Solved-Python

>What makes Python 'flow' with HTML nicely as compared to PHP?-Python

>What is data binding?-Angular





Submit
0 Answers