关闭

django模型自动创建

137人阅读 评论(0) 收藏 举报
分类:

应用场景,对于数据分表查询的时候,非常有用,比如历史某些数据比较大,每个月一个表,这就需要用到动态加载表。

# -*- coding: utf-8 -*-
from django.contrib import admin
from django.db import models

def create_model(model_name,  app_label='', fields=None, module='', meta_options=None, admin_options=None):
    """
    Create specified model
    """
    class Meta:
        # Using type('Meta', ...) gives a dictproxy error during model creation
        pass

    if app_label:
        # app_label must be set using the Meta inner class
        setattr(Meta, 'app_label', app_label)

    # Update Meta with any options that were provided
    if meta_options is not None:
        for key, value in meta_options.iteritems():
            setattr(Meta, key, value)

    # Set up a dictionary to simulate declarations within a class
    attrs = {'__module__': module, 'Meta': Meta}

    # Add in any fields that were provided
    if fields:
        attrs.update(fields)

    # Create the class, which automatically triggers ModelBase processing
    model = type(model_name, (models.Model,), attrs)

    # Create an Admin class if admin options were provided
    if admin_options is not None:
        class Admin(admin.ModelAdmin):
            pass
        for key, value in admin_options.items():
            setattr(Admin, key, value)
        admin.site.register(model, Admin)

    return model
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:88815次
    • 积分:1814
    • 等级:
    • 排名:千里之外
    • 原创:83篇
    • 转载:47篇
    • 译文:0篇
    • 评论:3条
    文章分类
    最新评论