Django跨数据库迁移和表结构迁移

备份数据库(备份app数据库)
python manage.py dumpdata authorization > authorization_data.json
同步数据库结构到slave(跨DB迁移)
python manage.py migrate --run-syncdb --database slave
同步数据到mysql数据库(导入数据)
python manage.py loaddata authorization_data.json

Django中ORM使用索引的话,会加快检索的速度,底层是B+树
在ORM中添加索引的两种方法:

方法1:在字段后面添加db_index=True
方法2:在模型的Meta属性类中添加参数:

class Meta:
indexes = [
models.Index(fields = [‘nikename’])#独立索引
models.Index(fields = [‘nikename’,“open_id”])#组合索引
]

Django中默认的索引规则:
主键必定是索引
外键是默认索引(也可以不是索引)

Django模型层-关系映射
三种关系映射
一对一的关系
一对多的关系(多对一)
多对多的关系

Django中的关系映射
一对一:OneToOneField
一对多:外键(Foreignkey)
多对多:ManyToManyField 只需要在一个类中添加即可

ORM中批量添加数据
def add_batch():
new_user_list = []
for i in range(10):
open_id = ranstr(32)
nike_name = ranstr(32)
user = UserProfile(open_id = open_id,nikename=nike_name)
new_user_list.append(user)
UserProfile.object.bulk_creat(new_user_lsit)

get 和filter的区别:
get是获取单个数据,查不到会报错
filter返回的是一个列表
批量查找
userobject.filter(open_id_contains = “123”)
批量删除
user.objec.filter(open_id_contains=“test_”).delete()
全部删除
user.objecr.all().delete()

批量修改
user.object.filter(opne_id_contains=“test_”).updata(nikename = “muuu”)

数据库函数:
字符串拼接:Concat
from django.db.model.functions import Concat
def concat_function():
user

查询常用的数据库函数"

in,pk相当于查询猪圈

gt 大于

Entry.objects.filter(id__gt=4)

SQL等效项:

SELECT ... WHERE id > 4;

gte大于或等于。

lt 少于。

lte小于或等于。

startswith

区分大小写的开头为。

例:

Entry.objects.filter(headline__startswith='Lennon')

SQL等效项:

SELECT ... WHERE headline LIKE 'Lennon%';

SQLite不支持区分大小写的LIKE语句。startswith就像istartswithSQLite一样。

istartswith

不区分大小写的开头为。

例:

Entry.objects.filter(headline__istartswith='Lennon')

SQL等效项:

SELECT ... WHERE headline ILIKE 'Lennon%';

endswith

区分大小写。

例:

Entry.objects.filter(headline__endswith='Lennon')

SQL等效项:

SELECT ... WHERE headline LIKE '%Lennon';

iendswith

不区分大小写的结尾为。

例:

Entry.objects.filter(headline__iendswith='Lennon')

SQL等效项:

SELECT ... WHERE headline ILIKE '%Lennon'

range

范围测试(含)。

例:

import datetime
start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
Entry.objects.filter(pub_date__range=(start_date, end_date))

SQL等效项:

SELECT ... WHERE pub_date BETWEEN '2005-01-01' and '2005-03-31';
发布了80 篇原创文章 · 获赞 0 · 访问量 1870

猜你喜欢

转载自blog.csdn.net/qq_37463791/article/details/104998187