Skip to content

Commit 59efb68

Browse files
committed
feat: add model caching to get_dynamics_model function in search.py
1 parent 2f12c61 commit 59efb68

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

apps/common/db/search.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
@date:2023/10/7 18:20
77
@desc:
88
"""
9+
import hashlib
910
from typing import Dict, Any
1011

1112
from django.db import DEFAULT_DB_ALIAS, models, connections
@@ -16,19 +17,37 @@
1617
from common.result import Page
1718

1819

20+
# 添加模型缓存
21+
_model_cache = {}
1922
def 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

3453
def generate_sql_by_query_dict(queryset_dict: Dict[str, QuerySet], select_string: str,

0 commit comments

Comments
 (0)