django動態生成數據庫表


from django.shortcuts import render, HttpResponse, HttpResponseRedirect
from django.contrib import admin
from django.db import models

# bfields = dict(
#     name=models.CharField(max_length=100),
#     authors=models.ManyToManyField(to='a', related_name='author')
# )

# afields=dict(title= models.CharField(choices=[('MR', 'Mr.'),
#                                                  ('MRS', 'Mrs.'),
#                                               ('MS', 'Ms.')], max_length=3),
#              birth_date= models.DateField(blank=True, null=True)
# )

from django.db import connection, migrations, models
from django.db.migrations.executor import MigrationExecutor


def create_table(table_name, model_fields, app_label):
    class Migration(migrations.Migration):
        initial = True
        dependencies = []
        operations = [
            migrations.CreateModel(
                name='a',
                fields=[
                    ('title', models.CharField(choices=[('MR', 'Mr.'), ('MRS', 'Mrs.'), ('MS', 'Ms.')], max_length=3)),
                    ('birth_date', models.DateField(blank=True, null=True)),
                ],
            ),
            migrations.CreateModel(
                name='b',
                fields=[
                    ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID')),
                    ('name', models.CharField(max_length=100)),
                    ('authors', models.ManyToManyField(to='a', related_name='author')),
                ],
            ),
            migrations.CreateModel(
                name='c',

                fields=[
                    ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID')),
                    ('name', models.CharField(max_length=32)),
                    ('data', models.CharField(db_index=True, max_length=32)),
                ],
            ),
        ]

    executor = MigrationExecutor(connection)
    migration = Migration(table_name, app_label)
    with connection.schema_editor(atomic=True) as schema_editor:
        migration.apply(executor._create_project_state(), schema_editor)


def get_model(name, fields=None, app_label=None, module='', options=None, admin_opts=None):
    """
    Create specified model
    """

    class Meta:
        db_table = name  # 這里和法1不同
        # pass

    if app_label:
        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)

    model = type(name, (models.Model,), attrs)
    return model


def tests(requests):
    # custom_model = create_table('example', fields,
    #                              app_label='app',
    #                           )
    afields = dict(title=models.CharField(choices=[('MR', 'Mr.'),
                                                   ('MRS', 'Mrs.'),
                                                   ('MS', 'Ms.')], max_length=3),
                   birth_date=models.DateField(blank=True, null=True)
                   )

    a_m = get_model('app01_a', app_label='app01', fields=afields)  # 參數1和法1不同

    bfields = dict(
        name=models.CharField(max_length=100),
        authors=a_m   # 這里和法1不同
    )
    model = get_model('app01_b', app_label='app01', fields=bfields)  # 參數1和法1不同

    # a_obj = obj.objects.get(id=1)
    print(model.objects.values('name'))
    obj = model.objects.filter(id=1).first()
    # a = obj
    a = obj.authors.objects.all()  # 參數1和法1不同
    print(a)

    return HttpResponse(a)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM