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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章