微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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))

原文地址:https://www.jb51.cc/mysql/433180.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐