django模型自动创建

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

# -*- 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
阅读更多
个人分类: django
上一篇mod_wsgi安装
下一篇supervisor的安装与配置
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭