Im working with FastAPI to create a really simple dummy API. For it I was playing around with enums to define the require body for a post request and simulating a DB call from the API method to a dummy method.
To have the proper body request on my endpoint, Im using Pydantic's BaseModel on the class definition but for some reason I get this error
File "pydantic/main.py", line 406, in pydantic.main.BaseModel.__setattr__
AttributeError: 'MagicItem' object has no attribute '__fields_set__'
Im not sure what's the problem, here is my code that's generate all this:
Im kinda lost right now cuz I don't see the error in such a simple code. Thanks in advance for the support ^^
CodePudding user response:
You basically completely discarded the Pydantic BaseModel.__init__
method on your MagicItem
. Generally speaking, if you absolutely have to override the Base Model's init-method (and in your case, you don't), you should at least call it inside your own like this:
super().__init__(...)
Pydantic does a whole lot of magic in the init-method. One of those things being the setting of the __fields_set__
attribute. That is why you are getting that error.
I suggest just completely removing your custom __init__
method.
One of the main benefits of using Pydantic models is that you don't have to worry about writing boilerplate like this. Check out their documentation, it is really good in my opinion.
PS:
If you insist because you want to be able to initialize your MagicItem
with positional arguments, you could just do this:
class MagicItem(BaseModel):
name: str
damage: Damage
def __init__(self, name: str, damage: Damage) -> None:
super().__init__(name=name, damage=damage)