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.

6 Upvotes

10 comments sorted by

View all comments

Show parent comment

3

u/bluewalt Dec 15 '24

Thanks for sharing, very interesting. In the meantime, I realized I was [not the only one] to struggle with relashionships and MappedAsDataclasses. For now, I'll remove them. The only downside is that sometimes I may need to override __init__ method.

I wanted to avoid SQLModel

Oh yes I just realized we already talked about this on this thread. Now I understand your message better.

But I think I'm now comfortable with separate Pydantic schemas (for input/output) and non-dataclass SQLAlchemy models. Even if there is some inevitable duplication at some point, it ways cleaner that SQLModel in my opinion. I can now know at a first glance what data lives my database, and what data the user need to fill, to create an object. More files, but less cognitive load :)

2

u/adiberk Dec 15 '24

You shouldn’t need to override the init. You can actually pass a param into each field that can exclude it from the init if you want

Assuming that is what you are asking for

1

u/bluewalt Dec 15 '24

Ohhhh...you're right! I assumed that because default_factory argument is not available without dataclass, I needed to override init method for the same purpose.

But, insert_default works perfectly! Thanks