Should I create mapper objects or use the declarative syntax in SQLAlchemy?

前端 未结 4 1298
北恋
北恋 2021-01-30 03:23

There are two (three, but I\'m not counting Elixir, as its not \"official\") ways to define a persisting object with SQLAlchemy:

Explicit syntax for mapper objects

4条回答
  •  清酒与你
    2021-01-30 04:01

    In our team we settled on declarative syntax.

    Rationale:

    • metadata is trivial to get to, if needed: User.metadata.
    • Your User class, by virtue of subclassing Base, has a nice ctor that takes kwargs for all fields. Useful for testing and otherwise. E.g.: user=User(name='doe', password='42'). So no need to write a ctor!
    • If you add an attribute/column, you only need to do it once. "Don't Repeat Yourself" is a nice principle.

    Regarding "keeping out ORM from business view": in reality your User class, defined in a "normal" way, gets seriously monkey-patched by SA when mapper function has its way with it. IMHO, declarative way is more honest because it screams: "this class is used in ORM scenarios, and may not be treated just as you would treat your simple non-ORM objects".

提交回复
热议问题