django orm动态建表

django orm动态建表

  • dynamic_models.py
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Author         : Charlie Zhang
# @Email          : [email protected]
# @Time           : 2021/7/16 17:31
# @Version        : 1.0
# @File           : dynamic_models.py
# @Software       : PyCharm
import datetime
import os
import sys
import django

sys.path.append("..")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()
from django.db import models, OperationalError


# name是表名,fields是字段,app_label是你的应用名(如:flow),module是应用下的模型(如:flow.models),options是元类选项
def create_model1(name, fields=None, app_label='', module='', options=None):
    class Meta:  # 模型类的Meta类
        pass

    if app_label:  # 必须在元类中设置app_label,相关属性可参考https://www.cnblogs.com/lcchuguo/p/4754485.html
        setattr(Meta, 'app_label', app_label)  # 更新元类的选项

    if options is not None:
        for key, value in options.items():
            setattr(Meta, key, value)  # 设置模型的属性
        attrs = {'__module__': module, 'Meta': Meta}  # 添加字段属性
    if fields:
        attrs.update(fields)  # 创建模型类对象
    return type(name, (models.Model,), attrs)


def install(custom_model):
    from django.db import connection
    from django.db.backends.base.schema import BaseDatabaseSchemaEditor
    editor = BaseDatabaseSchemaEditor(connection)
    try:
        editor.create_model(model=custom_model)  # 会抛出个异常,不知为啥,但表会创建
    except AttributeError as aerror:
        print(aerror)


def create_table(table_name) -> models.Model:
    marry_choices = (
        (0, '已婚'),
        (1, '未婚')
    )
    fields = {
        "name": models.CharField(max_length=30, verbose_name='姓名'),
        "id_card_num": models.CharField(max_length=18, verbose_name='身份证号码'),
        "gender": models.BooleanField(default=0, verbose_name='性别'),
        "age": models.IntegerField(verbose_name='年龄'),
        "email": models.CharField(max_length=80, verbose_name='邮箱'),
        "address": models.CharField(max_length=1024),
        "marry": models.IntegerField(choices=marry_choices, verbose_name='是否已婚'),
        "created_at": models.DateTimeField(auto_now_add=True, verbose_name='创建时间'),
        "updated_at": models.DateTimeField(auto_now=True, verbose_name='更新时间'),
        '__str__': lambda self: '%s' % (
            self.name,
        ), }
    options = {'ordering': [
        "-created_at"
    ], 'verbose_name': 'valued customer', }
    custom_model = create_model1(name=table_name, fields=fields, options=options, app_label='user',
                                 module='user.models')
    try:
        install(custom_model)  # 同步到数据库中
    except OperationalError as e:
        print(f'table {table_name} already exists')
    return custom_model


if __name__ == '__main__':
    date = datetime.datetime.now().strftime("%Y-%m")
    User = create_table(f'user_{date}')
    print(User.objects.count())

你可能感兴趣的:(django,orm)