django dynamic model

django model

首先对于一个习惯用django model的骚年来说,你肯定对django model自定制用的很熟悉,但突然让你用django dynamic model,也许会有很多人懵逼,然后各种查官网,看论坛,翻源码,终于搞出了。不过对于我们这些新手来说是相当吃力的。现在整理出来方便日后观看。

对于什么是django model 的定义就不多说

create table

在动态创建之前,应该先了解一下makemigrations以及migrate 的源码,先看看他们是如何生成的。下面是自己测试成功代码,仅供参考

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=‘app.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)

执行代码

    custom_model = create_table(‘example‘, fields,
                                 app_label=‘app‘,
                              )

注意 fields可自定制

执行成功后,你会发现你的数据表里多了这几个表

此时可不能万事大吉,怎么去操作也是很重要的。

操作danamic model

def get_model(name, fields=None, app_label=None, module=‘‘, options=None, admin_opts=None):
    """
    Create specified model
    """
    class Meta:
        db_table = name
    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

执行 get_model

al = dict(
    title=models.CharField(choices=[(‘MR‘, ‘Mr.‘), (‘MRS‘, ‘Mrs.‘), (‘MS‘, ‘Ms.‘)], max_length=3),
    birth_date=models.DateField(blank=True, null=True)
)
model_a = get_model(‘app_a‘, app_label=‘app‘, fields=al)

注意此时al 为你动态创建的model 字段,此时你获取该model时需要将字段传进去

而这此时也只是对单表操作,如果遇到manytomany呢?

那么别急,肯定会有解决的办法

哈哈

 model_a = get_model(‘app_a‘, app_label=‘app‘, fields=al)
    fields = dict(
        name=models.CharField(max_length=100),
        authors=model_a
    )

    modelb = get_model(‘app_b‘, app_label=‘app‘, fields=fields)
    obj = modelb.objects.filter(id=1).first()
    print(obj)
    a = obj.authors.objects.values(‘title‘)
    print(a)

即:如果你要正向操作,针对上面创建得表,你首先创建a表的类型,然后将a类型作为authors的参数传进去即可。

现在就一切OK了,  

  

  

  

原文地址:https://www.cnblogs.com/flash55/p/9064241.html

时间: 2024-08-06 09:38:19

django dynamic model的相关文章

django使用model创建数据库表使用的字段

Django通过model层不可以创建数据库,但可以创建数据库表,以下是创建表的字段以及表字段的参数.一.字段1.models.AutoField 自增列= int(11) 如果没有的话,默认会生成一个名称为 id 的列,如果要显示的自定义一个自增列,必须将给列设置为主键 primary_key=True.2.models.CharField 字符串字段 必须 max_length 参数3.models.BooleanField 布尔类型=tinyint(1) 不能为空,Blank=True4.

django创建model

django创建model 1. steps: new app add model class in app/models.py python manage.py migrate 2. model class 很简单,在models.py里面定义一个继承models.Model的类即可. # Create your models here. class Person(models.Model): name = models.CharField(max_length=30) 然后python ma

Python之路【第二十二篇】:Django之Model操作

Django之Model操作 一.字段 AutoField(Field) - int自增列,必须填入参数 primary_key=True BigAutoField(AutoField) - bigint自增列,必须填入参数 primary_key=True 注:当model中如果没有自增列,则自动会创建一个列名为id的列 from django.db import models class UserInfo(models.Model): # 自动创建一个列名为id的且为自增的整数列 usern

django中将model转换为dict的方法

django中将model转换为dict的方法 from django.forms.models import model_to_dict from user.model import userprofile model_to_dict(userprofile.model.get(id=100)) d3 = {'username': 'zz_yy', 'password': 'zyjzyj'} a = UserProfile() a.username = 'zz__e' a.password =

django的model字段在保存的时候做预处理怎么办?

django的model字段在保存的时候做预处理怎么办? 比如这个model: class Book(Model): publish_date = DateField() 但是在保存时,用户输入数据是: book1 = Book(publish_date='20171001') 我希望这个publish_date能够接受字符串输入,自动转为Date类型存入数据库.这个应该怎么处理呢?我现在这么处理,但是没用,还是报错说只接受2017-10-01格式的字符串 from dateutil.parse

Django操作model时,报错:AttributeError:’ProgrammingError’ object has no attribute ‘__traceback__’

原因:在Django项目下相应的应用下面的models.py配置的model(也就是class)没有创建成相应的表. 这是怎么回事呢? 首先,将models.py里面的model创建成对应的数据库表的执行命令(DOS命令)为:manage.py syncdb. 但是我自己的电脑上执行该命令时,显示.Unknown command:syncdb.执行,manage.py help后的确没有发现这个子命令.最后网上搜索发现这个命令已经在Django1.9里面取消了.并且stackoverflow里面

【Django】--Model字段

所有字段 AutoField(Field) --int自增列,必须填入参数primary_key=True BigAutoField(AutoField) --bigint自增列,必须填入参数primary_key=True 注意:当model中没有自增列,则自动会创建一个列名为id的列 from django.db import models class UserInfo(models.Model): #自动创建一个列名为id的且为自增的整数列 username = models.CharFi

Django: 之Model、Cookis、Session

到目前为止,当我们的程序涉及到数据库相关操作时,我们一般都会这么搞: 创建数据库,设计表结构和字段 使用MySQLdb来连接数据库,并编写数据访问层代码 业务逻辑层去调用数据访问层执行数据库操作 import MySQLdb def GetList(sql): db = MySQLdb.connect(user='root', db='wulaoerdb', passwd='1234', host='localhost') cursor = db.cursor() cursor.execute(

django中Model _meta API

Model _meta API的官方文档 https://docs.djangoproject.com/en/1.10/ref/models/meta/ Field access API >>> from django.contrib.auth.models import User # A field on the model >>> User._meta.get_field('username') <django.db.models.fields.CharFie