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

我很好奇如何在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))

相关文章

优化MySQL数据库发布系统存储的方法有:1.mysql库主从读写分...
使用mysql的方法:在“我的电脑”→右键→“管理”→“服务”...
在mysql中查看root用户权限的方法:1.命令行启动mysql服务;...
MySQL主从复制是用来备份一个与主数据库一样环境的从数据库,...
运行mysql的方法1.启动mysql服务,在“我的电脑”→右键→“...
开启mysql的方法1.可以通过快捷键win+r,输入cmd,打开窗口,...