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

pydantic: How to ignore invalid values when creating model instance

  • Thread starter Thread starter djangonaut
  • Start date Start date
D

djangonaut

Guest
Given a sample model:

Code:
from pydantic import BaseModel
from typing import Optional

class Foo(BaseModel):
     age: Optional[int]
     name: Optional[str]

I would like my model to be able to digest-but-ignore invalid values to receive an instance in any case. E.g.:

Code:
Foo(age="I", name="Jim")

should instead of raising a ValidationError automatically discard the value for the age field and results in

Code:
Foo(age=None, name='Jim')

I could manually loop over the ValidationErrors and drop the corresponding data or loop over the values and use validate_assignment, but I was thinking I am missing something built-in.
<p>Given a sample model:</p>
<pre><code>from pydantic import BaseModel
from typing import Optional

class Foo(BaseModel):
age: Optional[int]
name: Optional[str]
</code></pre>
<p>I would like my model to be able to digest-but-ignore invalid values to receive an instance in any case. E.g.:</p>
<pre><code>Foo(age="I", name="Jim")
</code></pre>
<p>should instead of raising a <code>ValidationError</code> automatically discard the value for the <code>age</code> field and results in</p>
<pre><code>Foo(age=None, name='Jim')
</code></pre>
<p>I could manually loop over the <code>ValidationErrors</code> and drop the corresponding data or loop over the values and use <code>validate_assignment</code>, but I was thinking I am missing something built-in.</p>
 
Top