135 model operation 2

Yesterday review

1 常用/非常用的字段和参数,元数据
	-常用字段
	-常用参数
	-元信息: 表名,联合索引,联合唯一索引
	
2 admin的使用(快速的对表增删查改)
	-创建超级用户
	-/admin/
	-把表在admin.py中注册
3 国际化
	-中文,时区问题
4 单表的新增,单表的删除,单表的修改
	-新增
		·对象.save
		·类名.object.create()
	-删除
		·Queryset.delete()
		·对象.delete()
		 对象.save
	-修改
		·对象.save()
		·Queryset.update()
5 单表查询
	-13个API
	filter,all,get,first,last,reverse,count,order_by,values,values_list,distinct,exclude,exist
	-模糊查询
	·__in
	·__range
	·__gt/lt/gte/lte
	·__year
	·__startswith
	·__endswith
	·__contains
	·__icontains

6 在脚本中调用django
7 打印原生sql

Today's content

1 Model creation of multi-table operation

1 图书表Book、作者表Author、作者详情表Author_detail、出版社表publisher
2 作者和作者详情:一对一
3 图书跟出版社:一对多,关系一旦确立,关联字段写在多的一方
4 图书和作者:多对多,需要建立第三张表(自动生成)

class Book(models.Model):
	title = models.CharField(max_length=64)
	price = models.DecimalField(max_digits=2, decimal_places=2)
	# to:跟哪个表关联(可以写字符串也可以写类名,写类名需先定义),to_field:跟哪个字段关联,可以不写,默认和主键关联
	# 2.x版本 外键字段必须加 参数on_delete, 1.x版本不需要
	publisher = models.ForeignKey(to='Publisher', to_field='id', on_delete=models.CASCADE, null=True)
	# 自动创建第三张表
	# 数据库中不存在该字段,没有to_field
	author = models.ManyToManyField('Author')
	# 时区相关
	# 默认存当前utc时间,
	# 中国是东八区,存到数据库中时间差8个小时
	# 通过设置,存东八区的时间,在配置文件中修改
	publish_date = models.DateField(auto_now_add=True)

	class Meta:
		# 表名
		db_table = "book"
		# 联合索引
		index_together = [
			('title', 'publisher'),
		]
		# 联合唯一索引
		# unique_together = (('title', 'publisher'),)

		# admin中显示的表名称
		verbose_name = '图书表'
		# verbose_name加s
		verbose_name_plural = '图书表'

	def __str__(self):
		return self.title


class Publisher(models.Model):
	name = models.CharField(max_length=64)
	city = models.CharField(max_length=32)

	def __str__(self):
		return self.name

	class Meta:
		db_table = 'publisher'
		verbose_name_plural = '出版社'


class Author(models.Model):
	name = models.CharField(max_length=64)
	age = models.IntegerField()
	details = models.OneToOneField('AuthorDetail')

	def __str__(self):
		return self.name

	class Meta:
		db_table = 'author'
		verbose_name_plural = '作者'


class AuthorDetail(models.Model):
	gender = models.SmallIntegerField()
	address = models.CharField(max_length=64)
	phone = models.BigIntegerField()

	class Meta:
		db_table = 'author_detail'
		verbose_name_plural = '作者信息'

2 Add records one-to-many

# 两种方式
publisher = models.Publisher.objects.create(name='北京出版社', city='北京')
# 1
	book = models.Book.objects.create(title='西游记', price='49.5', publisher=publisher)
# 2
	book = models.Book.objects.create(title='西游记', price='49.5', publisher_id=publisher.id)


# 总结:
	1 email可以不传email,本质就是varchar(admin中会判断)
    2 新增图书:
    	-publish=publish
        -publish_id=publish.id
    3 写在表模型中的publish字段,到数据库中会变成publish_id(ForeignKey)
    4 查到book对象以后
    	-book.publish     对象
    	-book.publish_id  id号,数字

3 Many-to-many add records, modify, delete

1 自动创建的表,表模型就拿不到,book.authors代指表模型


    # 多对多,作者和书
    # 给西游记这本书新增两个作者lqz和egon
    # 去到西游记这本书
    # book=models.Book.objects.get(name='西游记')
    # 代指中间表book.authors
    # lqz=models.Author.objects.get(id=2)
    # egon=models.Author.objects.get(id=3)
    # book.authors.add(2,3) # 新增作者,通过id新增
    # # book.authors.add(lqz,egon) # 新增作者,通过对象新增
    # book.authors.add(2,egon) # 新增作者,通过对象新增

    # 西游记删除一个作者
    # book = models.Book.objects.get(name='西游记')
    # book.authors.remove(2)
    # egon = models.Author.objects.get(id=3)
    # book.authors.remove(egon)

    # clear 清空所有作者
    book = models.Book.objects.get(name='西游记')
    # book.authors.add(2, 3)
    # book.authors.clear()

    # set 先清空,再add,前提是不存在的作者
    book.authors.set([4, ])
    
    # add ,remove,set clear

5 Object-based cross-table query


	# -基于对象的跨表查询: 子查询

	# 查询id为1的书,出版社所在的城市
	book = models.Book.objects.get(id=1)  # res = models.Book.objects.filter(id=1).first()
	pub = book.publisher  # 又执行了一次查询,根据publisher_id查询出publisher
	print(pub.city)

	# 北京出版社所有的书籍
	pub = models.Publisher.objects.get(name='北京出版社')
	books = pub.book_set.all()
	print(books)

	# 正向查询,book表中有publisher字段,直接对象.字段名
	# 反向查询, book表内没有book字段,出版社对象,表名小写_set.all()

	# 一对一查询
	# 查询所有住在北京的作者
	author_det = models.AuthorDetail.objects.filter(city='北京').first()
	# 反向
	print(author_det.author.name)

	# 查询作者egon的地址
	auth = models.Author.objects.get(name='egon')
	print(auth.author_detail.city)

	# 多对多关系查询
	# 正向
	# 西游记所有的作者的名字和手机号
	book = models.Book.objects.get(name='西游记')
	authors = book.author.all()
	for i in authors:
		print(authors.author_detail.phone)

	# 反向 查询egon出过所有书的名字
	obj = models.Author.objects.get(name='egon')
	books = obj.book_set.all()
	for i in books:
		print(i.title)

	# 总结:基于对象的跨表查询,先查对象,通过对象再去查一个对象(正向:字段名,反向:表名小写_set())




6 Cross-table query based on double underscore

	# -基于双下划线的跨表查询: 关联查询, 连表查询
	# 一对多:
	# 查询北京出版社出版书的名字和价格
	res = models.Publisher.objects.filter(name='北京出版社').values_list('book__title', 'book__price')
	print(res)
	res = models.Book.objects.filter(publisher__name='北京出版社').values('name', 'price')
	print(res)

	# 多对多
	# 查询egon出过所有书的名字
	res = models.Author.objects.filter(name='egon').values('book__title', 'book__price')
	res = models.Book.objects.filter(author__name='egon').values('title', 'price')

	# 一对一
	# 查询egon的手机号
	res = models.Author.objects.filter(name='egon').values('author_detail__phone')
	res = models.AuthorDetail.objects.filter(author__name='egon').values('phone')

	# 连续跨表查询
	# 查询北京出版社出版的书名和作者姓名
	res = models.Publisher.objects.filter(name='北京出版社').values('book__name','book__author__name')
	res = models.Book.objects.filter(publisher__name='北京出版社').values('title','author__name')
	res = models.Author.objects.filter(book__publisher__name='北京出版社').values('name','book__name')

	# 手机号以189开头的作者出版过的所有书籍名称以及出版社名称
	res = models.AuthorDetail.objects.filter(phone__contains='189').values('author__book__name',)

7Advanced continuous cross-table query

    # 连续跨表
    #查询北京出版社出版过的所有书籍的名字以及作者的姓名
    # res=models.Publish.objects.filter(name='北京出版社').values('book__name','book__authors__name')
    # print(res)

    # res=models.Book.objects.filter(publish__name='北京出版社').values('name','authors__name')
    # print(res)

    # res=models.Author.objects.filter(book__publish__name='北京出版社').values('book__name','name')
    # print(res)

    # 手机号以189开头的作者出版过的所有  书籍名称  以及   出版社名称
    # res=models.AuthorDetail.objects.filter(phone__startswith='189').values('author__book__name','author__book__publish__name')
    # print(res)

    # SELECT `app01_book`.`name`, `app01_publish`.`name` FROM `app01_author` INNER JOIN `app01_authordetail` ON (`app01_author`.`author_detail_id` = `app01_authordetail`.`id`) LEFT OUTER JOIN `app01_book_authors` ON (`app01_author`.`id` = `app01_book_authors`.`author_id`) LEFT OUTER JOIN `app01_book` ON (`app01_book_authors`.`book_id` = `app01_book`.`id`) LEFT OUTER JOIN `app01_publish` ON (`app01_book`.`publish_id` = `app01_publish`.`id`) WHERE `app01_authordetail`.`phone` LIKE  '189%' ;
    res=models.Author.objects.filter(author_detail__phone__startswith='189').values('book__name','book__publish__name')
    print(res)

Expand

1 Take a look at this blog

https://www.cnblogs.com/nokiaguy/p/13803370.html

2 Installation module related

pip3 install django    
# 本质是去https://pypi.python.org/simple,搜这个模块,会根据你的平台下载在一个安装包(windows平台是whl),下载完,再安装

# pip安装失败的情况
# 我们可以绕过它,有了whl文件以后,自己装
# https://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv
pip3 install django.whl   

# 官方库没有上传到pypi,官方也不给制作whl文件
#如何安装  包 (setup.py)
到达安装目录,setup.py所在的目录
python setup.py build
python setup.py install

# 配置清华源,豆瓣源,本质是
豆瓣源会把pypi,包拉到自己的服务器上,以后你再下,去它的服务器上下,所以速度快

# 你自己写的包,如何上传到pypi上给别人使用?

2 Do you want to establish a foreign key relationship?

1 关联字段与外键约束没有必然的联系(建管理字段是为了进行查询,建约束是为了不出现脏数据)
2 默认情况,关联关系建好以后,外键约束就自然建立了
3 实际工作中,外键约束一般不建(影响效率),都是人为约束(代码约束)
	-db_constraint=False
4 表模型和数据库表的对应,不要直接修改表(这是可以的,但是不建议),要修改表模型,同步到表中

operation

1 Finish talking

2 Other ways to write consecutively across tables

3 as follows (based on the object, based on the double slide down)

	# 查找所有书名里包含红楼的书
	res = models.Book.objects.filter(title__contains='红楼梦').all()
	print(res)
	# 查找出版日期是2017年的书
	res = models.Book.objects.filter(publish_date__year='2017').all()
	print(res)
	# 查找出版日期是2017年的书名
	for i in res:
		print(i.title)
	# 查找价格大于10元的书
	res = models.Book.objects.filter(price__gt=10).all()
	print(res)
	# 查找价格大于10元的书名和价格
	for i in res:
		print(i.title,i.price)
	# 查找在北京的出版社
	res = models.Publisher.objects.filter(city='北京').all()
	print(res)
	# 查找名字以沙河开头的出版社
	res = models.Publisher.objects.filter(name__startswith='沙河').all()
	print(res)
	# 查找作者名字里面带“小”字的作者
	res = models.Author.objects.filter(name__contains='小').all()
	print(res)
	# 查找年龄大于30岁的作者
	res = models.Author.objects.filter(age__lt=30).all()
	print(res)
	# 查找手机号是155开头的作者
	obj = models.AuthorDetail.objects.filter(phone__startswith='155').values('author__name')
	print(obj)
	# 查找手机号是155开头的作者的姓名和年龄
	obj = models.AuthorDetail.objects.filter(phone__startswith='155').values('author__name','author__age')
	print(obj)
	# 查找书名是“红楼梦”的书的出版社
	book = models.Book.objects.get(title='红楼梦')
	print(book.publisher)
	# 查找书名是“红楼梦”的书的出版社所在的城市
	res = models.Book.objects.filter(title='红楼梦').values('publisher__city')
	print(res)
	# 查找书名是“红楼梦”的书的出版社的名称
	res = models.Book.objects.filter(title='红楼梦').values('publisher__name')
	print(res)
	# 查找书名是“红楼梦”的书的所有作者
	res = models.Book.objects.filter(title='红楼梦').values('author__name')
	print(res)
	# 查找书名是“红楼梦”的书的作者的年龄
	res = models.Book.objects.filter(title='红楼梦').values('author__name','author__age')
	print(res)
	# 查找书名是“红楼梦”的书的作者的手机号码
	res = models.Book.objects.filter(title='红楼梦').values('author__authordetail__phone')
	print(res)
	# 查找书名是“红楼梦”的书的作者的地址
	res = models.Book.objects.filter(title='红楼梦').values('author__authordetail__address')
	print(res)
	# 查找书名是“红楼梦”的书的作者的邮箱
	# res = models.Book.objects.filter(title='红楼梦').values('author__authordetail__emailaddress')

Guess you like

Origin blog.csdn.net/qq_40808228/article/details/109096964