OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

What are the pros and cons of the two different declaritive methods in SQLAlchemy 2.0

  • Thread starter Thread starter Peter Kronenberg
  • Start date Start date
P

Peter Kronenberg

Guest
This page, https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#declarative-table-with-mapped-column, desribes two different ways of using Declarative Mapping

Declarative Table with mapped_column()

Code:
class User(Base):
    __tablename__ = "user"

    id = mapped_column(Integer, primary_key=True)
    name = mapped_column(String(50), nullable=False)
    fullname = mapped_column(String)
    nickname = mapped_column(String(30))

and then the Annotated Declarative Table, which ueses the Mapped object

Code:
class User(Base):
    __tablename__ = "user"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(50))
    fullname: Mapped[Optional[str]]
    nickname: Mapped[Optional[str]] = mapped_column(String(30))

The first one seems much more straight-forward. What are the advantages of the 2nd one? The type is specified twice, both as a Python type and as an SQLAlchemy type
<p>This page, <a href="https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#declarative-table-with-mapped-column" rel="nofollow noreferrer">https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#declarative-table-with-mapped-column</a>, desribes two different ways of using Declarative Mapping</p>
<p>Declarative Table with mapped_column()</p>
<pre><code>class User(Base):
__tablename__ = "user"

id = mapped_column(Integer, primary_key=True)
name = mapped_column(String(50), nullable=False)
fullname = mapped_column(String)
nickname = mapped_column(String(30))
</code></pre>
<p>and then the Annotated Declarative Table, which ueses the Mapped object</p>
<pre><code>class User(Base):
__tablename__ = "user"

id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(50))
fullname: Mapped[Optional[str]]
nickname: Mapped[Optional[str]] = mapped_column(String(30))
</code></pre>
<p>The first one seems much more straight-forward. What are the advantages of the 2nd one? The type is specified twice, both as a Python type and as an SQLAlchemy type</p>
 

Latest posts

B
Replies
0
Views
1
Blundering Ecologist
B
Top