python 构造和数据库更好关联的实体类
为了方便实体对象的插入,对实体类进行相关的设定,使得插入数据库的时候剩下很多事
alias静态属性字段,控制对应表中字段名和属性名的对应关系;
from typing import List class DemoEntity(object): alias = {} tab_name = None class Car(DemoEntity): alias = { "name1": "name", "age1": "age" } tab_name = "car" def __init__(self, name, age): self.name = name self.age = age T = DemoEntity or Car def transform_data(data_list: List[T], cls: T): alias_map = cls.alias tab_name = cls.tab_name columns = alias_map.keys() des_list = [] for data in data_list: des_data = [] for column in columns: attr_name = alias_map.get(column) attr_value = getattr(data, attr_name) des_data.append(attr_value) des_list.append(des_data) return tab_name, columns, des_list if __name__ == '__main__': car = Car("Model3", 8) tab_name, columns, des_list = transform_data([car], Car) print(tab_name) print(columns) print(des_list)