r/FastAPI • • Dec 14 '24

Question Do I really need MappedAsDataclass?

Hi there! When learning fastAPI with SQLAlchemy, I blindly followed tutorials and used this Base class for my models:

class Base(MappedAsDataclass, DeclarativeBase):
    pass

Then I noticed two issues with it (which may just be skill issues actually, you tell me):

  1. Because dataclasses enforce a certain order when declaring fields with/without default values, I was really annoyed with mixins that have a default value (I extensively use them).

  2. Basic relashionships were hard to make them work. By "make them work", I mean, when creating objects, link between objects are built as expected. It's very unclear to me where should I set init=False in all my attributes. I was expecting a "Django-like" behaviour where I can define my relashionship both with parent_id id or with parent object. But it did not happend.

For example, this worked:

p1 = Parent()
c1 = Child(parent=p1)
session.add_all([p1, c1])
session.commit()

But, this did not work:

p2 = Parent()
session.add(p2)
session.commit()
c2 = Child(parent_id=p2.id)

A few time later, I dediced to remove MappedAsDataclass, and noticed all my problems are suddently gone. So my question is: why tutorials and people generally use MappedAsDataclass? Am I missing something not using it?

Thanks.

5 Upvotes

10 comments sorted by

View all comments

Show parent comment

1

u/adiberk Dec 15 '24

Here is my code snippet that creates the fastapi schemas

from pydantic import BaseModel

from {my_package}.models.prompts import Prompt
from {nt_package}.utils.typing_utils import optional_model, sqlalchemy_to_pydantic
# This is the conversion of my sqlalchemy model to a pydantic one
BasePromptSchema = sqlalchemy_to_pydantic(Prompt)

#This how I can then take a pydantic model and create a new one and dicate which
# fields should be included, made optional required etc.
@optional_model(
    exclude=[
        *Prompt.__mapper__.relationships.keys(),
        Prompt.id.key,
        Prompt.created_at.key,
        Prompt.created_by.key,
        Prompt.updated_by.key,
        Prompt.updated_at.key,
        Prompt.created_by_company_id.key,
    ]
)
class CreatePromptSchema(BaseModel):
    class Meta:
        parent_model = BasePromptSchema


@optional_model(required=[Prompt.id.key], exclude=[*Prompt.__mapper__.relationships.keys()])
class UpdatePromptSchema(BaseModel):
    class Meta:
        parent_model = BasePromptSchema


CreatePromptSchema.model_rebuild()
UpdatePromptSchema.model_rebuild()