Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pydantic merge two members (Fields)

I have a example were I have an .env file what contains two variables:

PROJECT_NAME="dummy"
DB_URL=postgresql+psycopg2://postgres:postgres@postgres:5432/

In my config.py

class DummyConfig(BaseSettings):

    PROJECT: str = Field(...)

    DB_URL: str = Field(...)

Now depending on what project I will run, the PROJECT variable will be changed. I want to create full database url by concatenating PROJECT + DB_URL, and that needs to be a new (or in DB_URL) variable in config class. so in this example the result will be :

postgresql+psycopg2://postgres:postgres@postgres:5432/dummy

In class Config I want to have something like this:

class DummyConfig(BaseSettings):

    PROJECT: str = Field(...)

    DB_URL: str = Field(...) + PROJECT #this is for illustration purpose, I know it does not work

I have studied this post: Pydantic: How to use one field's value to set values for other fields?

But I do not understand (nor I can ask questions because of low points) how to do this. The OP was using user_dict that I assume was instantiated somewhere in the code. I do not have any dictionary, I am exclusively loading variable trough .env file.

like image 553
mehekek Avatar asked Oct 25 '25 02:10

mehekek


2 Answers

I think the easiest way for you to achieve this goal is by going around pydantic and just using a property.

class DummyConfig(BaseSettings):

    PROJECT: str = Field(...)

    DB_URL: str = Field(...)

    @property
    def FULL_DB_URL(self) -> str:
         return f"{self.DB_URL}/{self.PROJECT}"
like image 165
Robin Gugel Avatar answered Oct 26 '25 21:10

Robin Gugel


You can merge them inside environment variable

PROJECT_NAME="dummy"
FIRST_VARIABLE=postgresql+psycopg2://postgres:postgres@postgres:5432/

DB_URI=${FIRST_VARIABLE}${PROJECT_NAME}
like image 39
Rasim Mammadov Avatar answered Oct 26 '25 21:10

Rasim Mammadov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!