1

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.

mehekek
  • 113
  • 9

2 Answers2

2

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}"
Robin Gugel
  • 853
  • 3
  • 8
0

You can merge them inside environment variable

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

DB_URI=${FIRST_VARIABLE}${PROJECT_NAME}
Rasim Mammadov
  • 141
  • 1
  • 3