OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How to autopopulate fields on Pydantic model in Pydantic V2?

  • Thread starter Thread starter Zack Plauché
  • Start date Start date
Z

Zack Plauché

Guest
Say I have a model like this:

Code:
from pydantic import BaseModel

class MyModel(BaseModel):
    url: str
    id: str

I'd like to autofill the id field using data from the url.

Code:
url = 'https://www.example.com/open-requests/myid123'

instance = MyModel(url=url)
print(instance.id)  # 'myid123'

If I was using dataclasses, normally I'd just be able to overwrite the __post_init__ method and could do some extra stuff there. (Note: This method is still not optimal)

Code:
from dataclasses import dataclass

@dataclass
class MyModel:
    url: str
    id: str = None

    def __post_init__(self):
        self.id = self.url.split('/')[-1]

I'd like to not have to assign the id fields type to str | None = None.

How can I accomplish this?
<p>Say I have a model like this:</p>
<pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel

class MyModel(BaseModel):
url: str
id: str
</code></pre>
<p>I'd like to autofill the <code>id</code> field using data from the url.</p>
<pre class="lang-py prettyprint-override"><code>url = 'https://www.example.com/open-requests/myid123'

instance = MyModel(url=url)
print(instance.id) # 'myid123'
</code></pre>
<p>If I was using dataclasses, normally I'd just be able to overwrite the <code>__post_init__</code> method and could do some extra stuff there. (<strong>Note</strong>: This method is still not optimal)</p>
<pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass

@dataclass
class MyModel:
url: str
id: str = None

def __post_init__(self):
self.id = self.url.split('/')[-1]
</code></pre>
<p>I'd like to <strong>not</strong> have to assign the <code>id</code> fields type to <code>str | None = None</code>.</p>
<p>How can I accomplish this?</p>
 
Top