python - sqlalchemy : how can i map an existing class without modifying it?

标签 python sqlalchemy

我有一定数量的 python 类,我想使用 python sqlalchemy 将它们映射到数据库中的表。我看到了映射类派生自 sqlalchemy 基类的示例。我不想那样做。还有其他办法吗?

例如,如何映射这个简单的类?

class Person:
    def __init__(self, firstname: str = "x", name: str = "y", age: int = 0):
        self.firstname = firstname
        self.name = name
        self.age = age

    def __str__(self) -> str:
        return f"[{self.__firstname},{self.__name},{self.__age}]"

    @property
    def id(self):
       return self.__id

    @property
    def firstname(self) -> str:
        return self.__firstname

    @property
    def name(self) -> str:
        return self.__name

    @property
    def age(self) -> int:
        return self.__age

    # setters

    @id.setter
    def id(self, id: int):
        if not isinstance(id,int) or id<=0:
            raise MyException(f"...")

    @firstname.setter
    def firstname(self, firstname: str):
        if Utils.is_string_ok(firstname):
            self.__firstname = firstname.strip()
        else:
            raise MyException("...")

    @name.setter
    def name(self, name: str):
        if Utils.is_string_ok(name):
            self.__name = name.strip()
        else:
            raise MyException("...")

    @age.setter
    def age(self, age: int):
        error = False
        if isinstance(age, int):
            if age >= 0:
                self.__age = age
            else:
                error = True
        else:
            error = True
        if error:
            raise MyException("...")

我想将其映射到一个包含列(col1、col2、col3、col4)的表(例如与类属性不同的任意名称)。

最佳答案

对于任何感兴趣的人,我终于明白了(下面我更改了工作代码的标识符以匹配原始帖子):

# imports
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.orm import mapper, sessionmaker

from Person import Person

# mysql database
engine = create_engine("mysql+mysqlconnector://root@localhost/dbpersonnes")

# metadata
metadata = MetaData()

# table
persons_table = Table("persons", metadata,
                        Column('col1', Integer, primary_key=True),
                        Column('col2', String(30), nullable=False),
                        Column("col3", String(30), nullable=False),
                        Column("col4", Integer, nullable=False)
                        )

# mapping
mapper(Person, persons_table, properties={
    'id': persons_table.c.col1,
    'firstname': persons_table.c.col2,
    'name': persons_table.c.col3,
    'age': persons_table.c.col4,
})

# session factory
Session = sessionmaker()
Session.configure(bind=engine)

# session
session = Session()

# insert
session.add(Personne(67, "x", "y", 10))
session.commit()

# query
personnes = session.query(Personne).all()

# logs
for personne in personnes:
    print(personne)

关于python - sqlalchemy : how can i map an existing class without modifying it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61458069/

相关文章:

Python 检查日期是否为 future 30 天

python - Kivy:如何更改窗口大小?

当您使用 xpath 知道子文本时,python lxml 获取父元素

python - 在 jupyter notebooks : Validation fails when saving 中作图

python - 使用 pandas groupby 时数据丢失时 np.average 不起作用

python - 如何将 Redis 与 SQLAlchemy 集成

python - 在 SQLAlchemy 中手动构建 SQL 查询时如何正确转义字符串?

python - SQLAlchemy 偶尔会错误地返回空结果

python - SQLAlchemy func.count 带过滤器

python - sqlalchemy 的默认排序标准?