加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

mysql – 如何在django中创建临时表而不丢失ORM?

发布时间:2020-12-11 23:46:17 所属栏目:MySql教程 来源:网络整理
导读:我很好奇如何在django中创建一个临时表? (数据库是mysql,客户端要求) CREATE TEMPORARY TABLE somewhat_like_a_cache AS(SELECT * FROM expensive_query_with_multiple_joins);SELECT * FROM somewhat_like_a_cache LIMIT 1000 OFFSET X; 这背后的原因: 结

我很好奇如何在django中创建一个临时表? (数据库是mysql,客户端要求)

CREATE TEMPORARY TABLE somewhat_like_a_cache AS
(SELECT * FROM expensive_query_with_multiple_joins);
SELECT * FROM somewhat_like_a_cache LIMIT 1000 OFFSET X;

这背后的原因:
结果集相当大,我必须迭代它.昂贵的查询大约需要30秒.没有临时表,我会强调数据库服务器几个小时.使用临时表,昂贵的查询只执行一次,然后在切片中迭代临时表是很便宜的.

这不是重复的
How do I create a temporary table to sort the same column by two criteria using Django’s ORM?.作者只想按两列排序. 最佳答案 我遇到了这个问题,我构建了一个函数来将模型同步到数据库(改编自管理脚本syncdb).

您可以在代码中的任何位置编写临时模型,甚至可以在运行时生成模型,然后调用sync_models.并享受ORM

它的数据库独立,可以与任何django支持的数据库后端一起使用

from django.db import connection
from django.test import TestCase
from django.core.management.color import no_style
from importlib import import_module


def sync_models(model_list):
    '''
    Create the database tables for given models.
    '''
    tables = connection.introspection.table_names()
    seen_models = connection.introspection.installed_models(tables)
    created_models = set()
    pending_references = {}
    cursor = connection.cursor()
    for model in model_list:
        # Create the model's database table,if it doesn't already exist.
        sql,references = connection.creation.sql_create_model(model,no_style(),seen_models)
        seen_models.add(model)
        created_models.add(model)
        for refto,refs in references.items():
            pending_references.setdefault(refto,[]).extend(refs)
            if refto in seen_models:
                sql.extend(connection.creation.sql_for_pending_references(refto,pending_references))
        sql.extend(connection.creation.sql_for_pending_references(model,pending_references))
        for statement in sql:
            cursor.execute(statement)
        tables.append(connection.introspection.table_name_converter(model._meta.db_table))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读