目的:在数据库中动态添加表
环境:django-1.2, mysql-5.1.47
代码:
dynamic_model.py
# -*- coding: utf-8 -*- from django.db import models def create_model(name, fields=None, app_label='', module='', options=None, admin=None): 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 options is not None: for key, value in options.items(): 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 an Admin inner class if admin options were provided if admin is not None: class Admin: pass for key, value in admin: setattr(Admin, key, value) attrs['Admin'] = Admin # Create the class, which automatically triggers ModelBase processing return type(name, (models.Model,), attrs) def install(custom_model): from django.core.management import color from django.db import connection style = color.no_style() cursor = connection.cursor() statements, pending = connection.creation.sql_create_model(custom_model, style) for sql in statements: cursor.execute(sql)
view.py
在需要的地方添加
fields = { 'type' : models.CharField(max_length=100), 'category' : models.CharField(max_length=1024), 'title' : models.CharField(max_length=10240), 'answer' : models.CharField(max_length=200), '__str__' : lambda self : '%s %s %s %s' % (self.type, self.category, self.title, self.answer), } options = { 'ordering': ['type', 'category', 'title', 'answer'], 'verbose_name': 'valued customer', } admin = {} from django.utils.encoding import smart_str # convert unicode to string custom_model = create_model(smart_str(form.cleaned_data['basename']), fields, options=options, app_label='app', module='site.app', admin=admin) try: install(custom_model) #同步到数据库中 except: pass base = custom_model(title = form.cleaned_data['title'], answer = form.cleaned_data['answer'], type = form.cleaned_data['type'], category = form.cleaned_data['category']) base.save()
这样就在数据库中插入了一个表格