django动态创建表和动态选择实体

开发有时需要动态创建表,创建完成后需要动态选择model对应的表,该需求如何实现

1、model层   TestBlock为了动态创建表、getBlockModel为了动态选择表

复制代码
from django.db import models

# Create your models here.
class TestBlock(models.Model):
    BLOCK_ID = models.CharField(max_length=40,primary_key=True, verbose_name='对象ID')
    BLOCK_NAME = models.CharField(max_length=200, verbose_name='姓名')
    class Meta:
        db_table = 'TEST_BLOCK_T'
indexes = [
models.Index(fields=['BLOCK_ID'], name='BLOCK_ID _INDEX'),
models.Index(fields=['BLOCK_NAME'], name='BLOCK_NAME _INDEX'),
]

def getBlockModel(table_name): class MyCLass(models.Model): BLOCK_ID = models.CharField(max_length=40, primary_key=True, verbose_name='对象ID') BLOCK_NAME = models.CharField(max_length=200, verbose_name='姓名') class Meta: db_table = table_name return MyCLass
复制代码

2、url

1
2
3
4
5
6
7
8
9
from django.urls import path
 
 
from . import views
 
urlpatterns = [
      path('autoCreate', views.createTest),
      path('autoSelect', views.selectTest),
]

 3、view层createTest方法  重点的地方 注意红色地方,注释掉可以动态创建表,但是如果不注释掉,动态变更实体对应的数据表在使用它,就会报错

ERROR:django.db.utils.OperationalError: (1054, "Unknown column 'TEST_BLOCK_T_1.BLOCK_ID' in 'where clause'")

分别注释 #-------------1-begin-------------------------- 和 # -------------2-begin--------------------------之间的代码,执行代码动态创建两个表并把数据插入进去。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from django.shortcuts import render
 
# Create your views here.
from .models import *
from django.http import HttpResponse
from django.db import connection
 
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
 
 
def createTest(request):
    #-------------1-begin--------------------------
    TestBlock._meta.db_table = 'TEST_BLOCK_T_' + '1'
    # #创建分表
    cursor = connection.cursor()
    editor = BaseDatabaseSchemaEditor(connection)
    with BaseDatabaseSchemaEditor(connection) as editor:
        editor.create_model(model=TestBlock)
    # testBlock = TestBlock()
    # testBlock.BLOCK_ID = '1'
    # testBlock.BLOCK_NAME = 'oracle'
    # testBlock.save()
    # -------------1-end--------------------------
 
    # -------------2-begin--------------------------
    TestBlock._meta.db_table = 'TEST_BLOCK_T_' + '2'
    # #创建分表
    cursor = connection.cursor()
    editor = BaseDatabaseSchemaEditor(connection)
    with BaseDatabaseSchemaEditor(connection) as editor:
        editor.create_model(model=TestBlock)
 
    # testBlock1 = TestBlock()
    # testBlock1.BLOCK_ID = '2'
    # testBlock1.BLOCK_NAME = 'mysql'
    # testBlock1.save()
    # -------------2-end--------------------------
    return HttpResponse("yc is a good man")

 4、view层selectTest方法  动态选择实体对应的表

1
2
3
4
5
6
7
8
9
10
11
12
13
def selectTest(request):
    TestBlock = getBlockModel('TEST_BLOCK_T_' + '1')
    testBlocks = TestBlock.objects.all()
    for testBlock in testBlocks:
        print('1---testBlock.BLOCK_ID:'+testBlock.BLOCK_ID)
        print('1---testBlock.BLOCK_NAME:'+testBlock.BLOCK_NAME)
 
    TestBlock = getBlockModel('TEST_BLOCK_T_' + '2')
    testBlocks = TestBlock.objects.all()
    for testBlock in testBlocks:
        print('2---testBlock.BLOCK_ID:'+testBlock.BLOCK_ID)
        print('2---testBlock.BLOCK_NAME:'+testBlock.BLOCK_NAME)
    return HttpResponse("yc is a good man")

 数据结果:

1---testBlock.BLOCK_ID:1
1---testBlock.BLOCK_NAME:oracle
2---testBlock.BLOCK_ID:2
2---testBlock.BLOCK_NAME:mysql

结论是 TestBlock._meta.db_table = 'TEST_BLOCK_T_' + '1'可以动态创建表,而动态选择表只能用TestBlock = getBlockModel('TEST_BLOCK_T_' + '1') 这样的方式。

 

资源丰富的的网盘资源:网盘资源大全! 推荐一个适合零基础学习SQL的网站:不用安装数据库,在线轻松学习SQL!
posted @   万笑佛  阅读(983)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示