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了,  

  

  

  

django dynamic model的更多相关文章

  1. Django之Model操作

    Django之Model操作 本节内容 字段 字段参数 元信息 多表关系及参数 ORM操作 1. 字段 字段列表 AutoField(Field) - int自增列,必须填入参数 primary_ke ...

  2. Django的Model上都有些什么

    Django的Model上都有些什么 modelinfo= ['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__' ...

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

    Django之Model操作   一.字段 AutoField(Field) - int自增列,必须填入参数 primary_key=True BigAutoField(AutoField) - bi ...

  4. django User model

    django User model operation this tutorial will guide us to know how to manipulate django User model. ...

  5. Scrapy中使用Django的Model访问数据库

    Scrapy中使用Django的Model进行数据库访问 当已存在Django项目的时候,直接引入Django的Model来使用比较简单 # 使用以下语句添加Django项目的目录到path impo ...

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

    Django通过model层不可以创建数据库,但可以创建数据库表,以下是创建表的字段以及表字段的参数.一.字段1.models.AutoField 自增列= int(11) 如果没有的话,默认会生成一 ...

  7. Django之Model组件

    Model组件在django基础篇就已经提到过了,本章介绍更多高级部分. 一.回顾 1.定义表(类) ##单表 from django.db import models class user(mode ...

  8. django中将model转换为dict的方法

    django中将model转换为dict的方法 from django.forms.models import model_to_dict from user.model import userpro ...

  9. Python学习---django之Model语法180124

    django之Model语法[Models] 1    django默认支持sqlite,mysql, oracle,postgresql数据库. <1> sqlite django默认使 ...

随机推荐

  1. Android Afinal框架学习(一) FinalDb 数据库操作

    框架地址:https://github.com/yangfuhai/afinal 对应源码: net.tsz.afinal.annotation.sqlite.* net.tsz.afinal.db. ...

  2. tf随笔-5

    # -*- coding: utf-8 -*-import tensorflow as tfw1=tf.Variable(tf.random_normal([2,6],stddev=1))w2=tf. ...

  3. Arcgis for Js之Graphiclayer扩展详解

    在前两节,讲到了两种不同方式的聚类,一种是基于距离的,一种是基于区域范围的,两种不同的聚类都是通过扩展esri/layers/GraphicsLayer方法来实现的.在本节,就详细的讲讲esri/la ...

  4. Android内存优化(二)DVM和ART的GC日志分析

    相关文章 Android内存优化系列 Java虚拟机系列 前言 在Java虚拟机(三)垃圾标记算法与Java对象的生命周期这篇文章中,提到了Java虚拟机的GC日志.DVM和ART的GC日志与Java ...

  5. C++中cin的使用总结

    在学习C++时大家肯定迷惑过关于输入输出各种输出函数的功能,现在来总结一下各种函数的简单用法. cin建有一个缓冲区,即输入缓冲区.一次输入过程是这样的,当一次键盘输入结束时会将输入的数据存入输入缓冲 ...

  6. win键盘映射成mac键盘

    在win7系统下安装了mac虚拟机,mac的快捷键与win的键盘不一样,所以ctrl+c,ctrl+v都用不了,于是找方法映射. 搜索到 keyremap4macbook,,进到官网Karabiner ...

  7. SMMS 2016 啟用深色主題

    1.用文本類編輯器 打開C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio目錄下的 ssms.pkg ...

  8. numpy之统计函数和布尔数组方法

    统计函数 可以通过numpy的统计函数对整个数组或者某个轴向的数据进项统计计算. 所谓的轴向,其实就是n维向量的某一维.或者说某一行,某一列. sum对数组(向量)中全部或某个轴向的元素求和,长度为0 ...

  9. asp select count(*) 用 open还是excute

    dSql1="select count(*) from test_hist where uid="&cid  'dRs1.open dSql1,tConn,1,1  'dS ...

  10. jinja2的一些用法

    1.split用法以及乘法运算 {% set user_list=l.users.split(',') %} <tr> <td>{{ l.name }}</td> ...