what we need use Mapped() and mappedcolumn in sqlalchemy for? I can anderstad the…
- User
what we need use Mapped() and mapped_column in sqlalchemy for? I can anderstad the difference between this one for instance class Log(Base): tablename = "log"
id = Column(Integer, primary_key=True, autoincrement=True) request_datetime = Column(TIMESTAMP(timezone=True), nullable=False) request_url = Column(Text, nullable=False) request_method = Column(String(8), nullable=False) - Assistant
The mapped() function in SQLAlchemy is used to map an existing class to a specific table in a database. This means that it allows you to create a mapping between the attributes of the class and the columns in the table.
The mapped_column() function is used to map an individual attribute of a class to a specific column in a database table. This is useful if you want to map specific attributes of a class to specific columns in the database, rather than using the default mapping generated by SQLAlchemy.
In the example you provided, the class Log is being mapped to a table called "log" in the database. The attributes of the class (id, request_datetime, request_url, and request_method) are being mapped to columns in the "log" table.
- User
I mean this syntax class User(Model): tablename = 'users'
id: so.Mapped[int] = so.mapped_column(primary_key=True) username: so.Mapped[str] = so.mapped_column(sa.String(64), index=True, unique=True) email: so.Mapped[str] = so.mapped_column(sa.String(120), index=True, unique=True) password_hash: so.Mapped[Optional[str]] = so.mapped_column(sa.String(128)) about_me: so.Mapped[Optional[str]] = so.mapped_column(sa.String(140)) - Assistant
The syntax you provided is for defining a SQLAlchemy model class called
Userwhich represents a table in the database calledusers.Each attribute in the class corresponds to a column in the database table and is defined using the
so.mapped_column()function. TheMappedclass within thesqlalchemy.ormmodule is used to define the data type of the column, and themapped_column()function is used to specify any additional attributes such as primary keys, indexes or unique constraints.For example, the
idattribute is defined as a primary key column using theso.mapped_column(primary_key=True)syntax. Theusernameandemailattributes are defined with unique constraints usingso.mapped_column(sa.String(64), index=True, unique=True)andso.mapped_column(sa.String(120), index=True, unique=True)respectively.By defining the attributes of the class using
Mappedandmapped_column(), you can easily create, update and query the database table using SQLAlchemy's object-relational mapping capabilities. - User
So what difference beteen this way class Log(Base): tablename = "log"
id = Column(Integer, primary_key=True, autoincrement=True) request_datetime = Column(TIMESTAMP(timezone=True), nullable=False) request_url = Column(Text, nullable=False) request_method = Column(String(8), nullable=False) - Assistant
The difference between the two ways of defining SQLAlchemy models is in the use of type hints with the
Mappedandmapped_column()functions in the first example.In the first example, the
Mappedclass andmapped_column()function are imported from thesqlalchemy.ext.declarativemodule and used in conjunction with type hints to define the data type of the column. This makes the code more readable and easier to understand as it clearly shows the data types of the columns.In the second example, the columns are defined using the
Column()function without type hints. This means that the data types of the columns are not explicitly specified and are inferred from the type of object passed to theColumn()function. While this reduces code clutter, it can make it harder to understand the data types of the columns, especially in a large schema with many tables and columns.Both ways are valid and work fine with SQLAlchemy. The choice between them usually comes down to personal preference and coding style.
- User
rewrite this with mapped class Log(Base): tablename = "log"
id = Column(Integer, primary_key=True, autoincrement=True) request_datetime = Column(TIMESTAMP(timezone=True), nullable=False) request_url = Column(Text, nullable=False) request_method = Column(String(8), nullable=False) response_datetime = Column(TIMESTAMP(timezone=True), nullable=False) response_status_code = Column(SmallInteger, nullable=False) response_error_type = Column(String(2), nullable=False) response_error_number = Column(String(2), nullable=False) response_error_code = Column(String(5), nullable=True) phone_number = Column(String(10), nullable=True) duration = Column(Interval, nullable=False) - Assistant
Here is the rewritten code for the
Logclass using theMappedandmapped_column()functions with type hints:from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import mapped from sqlalchemy import Column, Integer, String, SmallInteger, Text, TIMESTAMP, Interval Base = declarative_base() class Log(Base): __tablename__ = "log" id: mapped[int] = mapped_column(primary_key=True) request_datetime: mapped[datetime] = mapped_column(TIMESTAMP(timezone=True), nullable=False) request_url: mapped[str] = mapped_column(Text, nullable=False) request_method :mapped[str] = mapped_column(String(8), nullable=False) response_datetime: mapped[datetime] = mapped_column(TIMESTAMP(timezone=True), nullable=False) response_status_code: mapped[int] = mapped_column(SmallInteger, nullable=False) response_error_type: mapped[str] = mapped_column(String(2), nullable=False) response_error_number: mapped[str] = mapped_column(String(2), nullable=False) response_error_code: mapped[str] = mapped_column(String(5), nullable=True) phone_number: mapped[str] = mapped_column(String(10), nullable=True) duration : mapped[timedelta] = mapped_column(Interval, nullable=False)In this code, we import the
declarative_base()function from SQLAlchemy and use it to create our base classBase. We also import themappedclass andmapped_column()function from thesqlalchemy.ormmodule and use them to define the data types of our columns with type hints. Each attribute in the class corresponds to a column in the database table and is defined using themapped_column()function.Note that the data types in the type hints (
datetime,timedelta, andint) are not native Python types but rather the types defined in SQLAlchemy. Also, since we are using type hints, we do not need to use thenullableparameter as it is specified in the type hint.