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了,
django dynamic model的更多相关文章
- Django之Model操作
Django之Model操作 本节内容 字段 字段参数 元信息 多表关系及参数 ORM操作 1. 字段 字段列表 AutoField(Field) - int自增列,必须填入参数 primary_ke ...
- Django的Model上都有些什么
Django的Model上都有些什么 modelinfo= ['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__' ...
- Python之路【第二十二篇】:Django之Model操作
Django之Model操作 一.字段 AutoField(Field) - int自增列,必须填入参数 primary_key=True BigAutoField(AutoField) - bi ...
- django User model
django User model operation this tutorial will guide us to know how to manipulate django User model. ...
- Scrapy中使用Django的Model访问数据库
Scrapy中使用Django的Model进行数据库访问 当已存在Django项目的时候,直接引入Django的Model来使用比较简单 # 使用以下语句添加Django项目的目录到path impo ...
- django使用model创建数据库表使用的字段
Django通过model层不可以创建数据库,但可以创建数据库表,以下是创建表的字段以及表字段的参数.一.字段1.models.AutoField 自增列= int(11) 如果没有的话,默认会生成一 ...
- Django之Model组件
Model组件在django基础篇就已经提到过了,本章介绍更多高级部分. 一.回顾 1.定义表(类) ##单表 from django.db import models class user(mode ...
- django中将model转换为dict的方法
django中将model转换为dict的方法 from django.forms.models import model_to_dict from user.model import userpro ...
- Python学习---django之Model语法180124
django之Model语法[Models] 1 django默认支持sqlite,mysql, oracle,postgresql数据库. <1> sqlite django默认使 ...
随机推荐
- postgresql recovery.conf文件内容说明
在配置PG主备流复制.HA时,需要用到recovery.conf文件,这里根据自己的了解做个记录: standby_mode = 'on' #说明自己是备库 primary_conninfo = 'u ...
- Qt 出现“undefined reference to `vtable for”原因总结
http://blog.csdn.net/chenlong12580/article/details/7431104
- Python正则表达式使用过程中的小细节
今天用Python写了个简单的爬虫程序,抓取虎扑篮球(nba.hupu.com)的首页内容,代码如下: #coding:gb2312 import urllib2, re webpage = urll ...
- 边缘检测︱基于 HED网络TensorFlow 和 OpenCV 实现图片边缘检测
本文摘录自<手机端运行卷积神经网络的一次实践 – 基于 TensorFlow 和 OpenCV 实现文档检测功能> 只截取感兴趣 的片段. . 一.边缘检测 1.传统边缘检测 Google ...
- java网络编程TCP传输—流操作—服务端反馈与客户端接收
在读取完流后,服务端会向客户端返回一些数据,告诉客户端,已经写完了. 在这里和”流操作—拿到源后的写入动作“差不多,客户端同样以byte与Buffered两种缓冲读取作为例子,同时,.也是希望大家给补 ...
- LeetCode Design TinyURL
原题链接在这里:https://leetcode.com/problems/design-tinyurl/description/ 题目: How would you design a URL sho ...
- .NET系统框架
本书是一本讲解.NET技术的书籍,目标读者群也是在.NET框架(.NET Framework)下进行开发的程序员,因此我们无法回避的问题就是:什么是.NET框架?它包含了哪些内容?为开发程序提供了哪些 ...
- iframe添加点击事件
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...
- (转)Android高性能编程(1)--基础篇
关于专题 本专题将深入研究Android的高性能编程方面,其中涉及到的内容会有Android内存优化,算法优化,Android的界面优化,Android指令级优化,以及Android应用内存占 ...
- IaaS vs PaaS vs SaaS
在云计算的早期阶段,企业面临的最大问题是他们是否应该使用公共云服务.如今,几乎所有的组织都在采用一些公共云服务.更重要的问题是企业应该使用哪种云服务:基础设施即服务(IaaS),平台即服务(PaaS) ...