Django进阶之关联表、模糊查询、分页器

一、Django数据库的设置(sqllite3)

1、sqllite3数据库的配置

1)假如出现os问题,一般是settings文件没有引入os,直接import os即可

2)使用sqlite3数据库的settings文件设置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

3)右边添加数据库 

Django进阶之关联表、模糊查询、分页器_第1张图片

4)使用mysql数据库的settings文件设置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': '127.0.0.1',  # 数据库主机
        'PORT': 3306,  # 数据库端口
        'USER': 'root',  # 数据库用户名
        'PASSWORD': '123456',  # 数据库用户密码
        'NAME': 'exx'  # 数据库名字
    }
}

5)数据库更新

构造表结构数据库python manage.py makemigrations

迁移数据库python manage.py migrate

二、关联表

1、创建一对多的外键和多对多的关联表

#创建一个publish_id的外键,db_constraint=False表示不创建外键的约束。
#不创建外键约束的原因是操作表有约束就会浪费资源去查链接的表,不管是否有需求,导致资源浪费。
#同时还会关联一个publish对象,一对多的关系
publish=models.ForeignKey(Publish, on_delete=models.CASCADE(), db_constraint=False, default=1)

#多对多的关系,创建一个关联表,通过author可以对表进行增删改查,db_table定义表名
authors=models.ManyToManyField(Author,db_table="book2author")

2、关联表的增删改查

def add(request):
# 针对一对多的添加记录
# 方式1
# pub = Publish.objects.get(name="苹果出版社")
# book = Book.objects.create(title="西游记", price=199, pub_date="2012-12-12", publish=pub)
# 方式2
# book = Book.objects.create(title="红楼梦", price=299, pub_date="2011-12-12", publish_id=2)
# print(type(book.id))

# 多对多的添加记录

# book = Book.objects.create(title="飘", price=399, pub_date="2018-12-12", publish_id=2)
# print(type(book.id))
# print(book.title)
# print(book.price)
# print(book.publish_id)
# book.publish  : book书籍的出版社对象
# print(book.publish) # orm:  return publish = Publish.objects.get(id=book.publish_id)
# print(book.publish.name)

# 给book绑定作者关系 book.authors的多对多字段是对应关系表的增删改查的管理器对象

# 查询yuan和rain作者(增)
# 方式1
# yuan = Author.objects.get(name="yuan")
# rain = Author.objects.get(name="rain")
# book.authors.add(yuan, rain)
# 方式2 给当前数据模型添加几个作者
# book.authors.add(1, 2)
# 方式3 *打散
# book.authors.add(*[1, 2])

#  删除多对多记录(删)
# book = Book.objects.get(title="三体")
# book.authors.remove(1,2)
# book.authors.remove(*[1,2])

# book.authors.clear()#清除当前书籍对应的作者
# book.authors.set()  # clear+add

# set方法:重新设置书籍作者关联表(改)
方式一:
# book.authors.clear()
# book.authors.add(2)
方式二:
# book.authors.set([2])

# 多对多查询:查询三体所有作者的名字(查)
# book = Book.objects.get(title="三体")
# book.authors.all() # orm return 2 Author.objects.filetr(id in [1,2])   1 book_authors.objects.filter(book_id=book.id).values("author_id")

3、模糊查询

book.objects.filter(price__gt=100);#select * from book where price>100
book.objects.filter(price__lt=100);#select * from book where price<100
book.objects.filter(name__contains='水');#select * from book where name='%水%'
book.objects.filter(name__startswith='水');#select * from book where name='水%'
book.objects.filter(name__endswith='水');#select * from book where name='%水'

4、分页器

from django.core.paginator import Paginator
#第一个参数是数据列表,第二个参数代表3个数据分一页
paginatior = Paginator([111,222,333,444,555,666,777,888,999,1000],3)
#查总页码 结果:4
paginatior.num_pages

#查询总条数 10
paginatior.count

#取数据,取头不取尾
paginatior.page_range
#range(1, 5)
取第一页的数据
page = paginatior.page(1)
page1 = paginatior.page(1)
page1.object_list
"""
[111, 222, 333]
[i for i in page1]
[111, 222, 333]
"""
page1 = paginatior.page(4)
page4 = paginatior.page(4)
[i for i in page4]
[1000]
page4 = paginatior.page(5)
"""
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python3.7/site-packages/django/core/paginator.py", line 70, in page
    number = self.validate_number(number)
  File "/usr/local/lib/python3.7/site-packages/django/core/paginator.py", line 52, in validate_number
    raise EmptyPage(_('That page contains no results'))
django.core.paginator.EmptyPage: That page contains no results
"""
page4.has_previous()
#True
page4.previous_page_number()
#3
page4.has_next()
#False

你可能感兴趣的:(python,django,python,后端)