Pydantic and subclasses

Kendrick Lamar :

I have this project where my base class and my sub-classes implement pydantic.BaseModel:

from pydantic import BaseModel
from typing import List
from dataclasses import dataclass

@dataclass
class User(BaseModel):
    id: int 

@dataclass
class FavoriteCar(User):
    car_names: List[str] 

car = FavoriteCar(id=1, car_names=["Acura"])
print(f"{car.id} {car.car_names[0]}")

But this error appears:

    self.__fields_set__.add(name)
E   AttributeError: __fields_set__

Does someone mind explaining what is going on? The reason why I want to use pydantic is because I need a way to quickly convert Python objects to dict (or JSON) and back.

Peter Thomassen :

You need to decide whether to inherit from pydantic.BaseModel, or whether to use the @dataclass decorator (either from dataclasses, or from pydantic.dataclasses).

Either is fine, but you cannot use both, according to the documentation (bold face added by myself):

If you don't want to use pydantic's BaseModel you can instead get the same data validation on standard dataclasses

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=5168&siteId=1