Stop pydantic validation for nested pydantics

36 Views Asked by At

I use a pydantic class to create a profile with field validations like email for example. When I create a single profile, these validations are necessary. But when I massively add dozens of profiles to a list of profiles, I would like this validation to disappear because I will later check each profile by browsing the list. The idea is that I don't want a massive scrap to be stopped if a profile isn't good. We know that sometimes scrap has waste.

I don't want to loose Email validation when creating 1 profil

How do you do this please?

class Profil(BaseModel):
    pseudo: str
    mail: EmailStr
    page_url: str
    social_network: str
    created_date: datetime = Field(default_factory=datetime.now)

In my DTO file for bulk insert where I don't want Raise ValueError if email is not correct


class InsertListProfilInputDto(BaseModel):
    """Input Dto for bulk insert of profil"""

    data: list[Profil]

Thank you

1

There are 1 best solutions below

0
Dadoo On
from datetime import datetime
from pydantic import BaseModel, EmailStr, Field


class Influenceur(BaseModel):
   pseudo: str
   mail: EmailStr
   page_url: str
   social_network: str
   created_date: datetime = Field(default_factory=datetime.now)


class BulkInsertInfluenceurInputDto(BaseModel):
    data: list[Influenceur]

    @model_validator(mode="wrap")  # type: ignore
    def bypass_incorrect_profil(cls, kwargs: dict[str, Any], handler):
        for profil in kwargs["data"][:]:
            try:
                Influenceur(**profil)
            except Exception:
                kwargs["data"].remove(profil)
        return handler(kwargs)

In my endpoint with fast fastapi with this datas in body

{
  "data": [
    {
      "pseudo": "bob",
      "mail": "[email protected]",
      "page_url": "http://example.com",
      "social_network": "instagram",
      "created_date": "2024-03-22T11:06:44.002Z"
    },
{
      "pseudo": "marc",
      "mail": "marcexample.com", -------> this emailis Wrong and will raise Error in Influenceur.mail : EmailStr
      "page_url": "http://example.com",
      "social_network": "instagram",
      "created_date": "2024-03-22T11:06:44.002Z"
    }
  ]
}


@router.post("/")
async def bulk_insert(input_dto: BulkInsertInfluenceurInputDto):
    print(input_dto)

results only bob (correct email ) is returned:

[{'pseudo': 'bob', 'mail': '[email protected]', 'page_url': 'http://example.com', 'social_network': 'instagram', 'created_date': '2024-03-22T11:06:44.002Z'}]