File tree Expand file tree Collapse file tree 1 file changed +20
-1
lines changed
Expand file tree Collapse file tree 1 file changed +20
-1
lines changed Original file line number Diff line number Diff line change 66 @date:2023/10/7 18:20
77 @desc:
88"""
9+ import hashlib
910from typing import Dict , Any
1011
1112from django .db import DEFAULT_DB_ALIAS , models , connections
1617from common .result import Page
1718
1819
20+ # 添加模型缓存
21+ _model_cache = {}
1922def get_dynamics_model (attr : dict , table_name = 'dynamics' ):
2023 """
2124 获取一个动态的django模型
2225 :param attr: 模型字段
2326 :param table_name: 表名
2427 :return: django 模型
2528 """
29+ # 创建缓存键,基于属性和表名
30+ cache_key = hashlib .md5 (f"{ table_name } _{ str (sorted (attr .items ()))} " .encode ()).hexdigest ()
31+ # print(f'cache_key: {cache_key}')
32+
33+ # 如果模型已存在,直接返回缓存的模型
34+ if cache_key in _model_cache :
35+ return _model_cache [cache_key ]
36+
2637 attributes = {
2738 "__module__" : "knowledge.models" ,
2839 "Meta" : type ("Meta" , (), {'db_table' : table_name }),
2940 ** attr
3041 }
31- return type ('Dynamics' , (models .Model ,), attributes )
42+
43+ # 使用唯一的类名避免冲突
44+ class_name = f'Dynamics_{ cache_key [:8 ]} '
45+ model_class = type (class_name , (models .Model ,), attributes )
46+
47+ # 缓存模型
48+ _model_cache [cache_key ] = model_class
49+
50+ return model_class
3251
3352
3453def generate_sql_by_query_dict (queryset_dict : Dict [str , QuerySet ], select_string : str ,
You can’t perform that action at this time.
0 commit comments