基于表关系的增删改查
Posted wrqysrt
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于表关系的增删改查相关的知识,希望对你有一定的参考价值。
创建四表,author,book,publish,author-detail 存在多对多,一对一,多对一的关系
在models里创建
class Pulish(models.Model):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=32)
address=models.CharField(max_length=32)
class Book(models.Model):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=32)
price=models.DecimalField(max_digits=5,decimal_places=2)
publish_date=models.DateField()
pulish=models.Foreignkey(to=Pulish,to_field=id)
author=models.ManyToManyField(to=Author,to_field=id)
class Author(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
author_detail = models.OneToOneField(to=‘AuthorDetail‘, to_field=‘id‘)
class AuthorDetail(models.Model):
id = models.AutoField(primary_key=True)
age = models.IntegerField()
telephone = models.BigIntegerField()
info = models.TextField()
在test测试
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dj01.settings")
django.setup()
单对单的增删改查
增加
detail=Author_detail.objects.create()
Author.objects.create(author_detail=detail)或者(author_detail_id=detail_id)
删除
删除被依附表字段,依附表会删除
Author.objects.last().delete()
# Author.objects.filter()[2].delete()
一对一不考虑更新
查询
# 连表查询规则
# 1. 正向逆向概念:从存放外键的表到关系表称之为正向跨表查询,反之称之为逆向查询
# 2. 正向查询通过外键属性名进行跨表查询
# 3. 逆向查询通过关联表对应类名小写进行跨表查询
# 在连表查询规则规则之上,逆向查询遇到多条结果,在类名后再添加_set
# author=Author.objects.first()
# print(author.author_detail.age)
#
# print(AuthorDetail.objects.first().author.name)
多对一
# publish=Publish.objects.create(name=‘oldboy‘,address=‘上海‘)
# publish=Publish.objects.create(name=‘商务出版社‘,address=‘北京‘)
# book=Book.objects.create(name=‘老人与海‘,price=666.66,publish_date=‘2018-8-8‘,publish_id=1)
# book=Book.objects.create(name=‘谁的青春不迷茫‘,price=66.66,publish_date=‘2016-6-6‘,publish_id=3)
# book=Book.objects.create(name=‘洛丽塔‘,price=166.66,publish_date=‘2006-3-3‘,publish_id=3)
# Book.objects.filter(id=1).delete()
# Publish.objects.filter(id=2).delete()
# 删除被依附表字段,依附表会删除
# book=Book.objects.filter(id=2)[0]
# book.publish_id=2
# book.save()
查询
# print(Book.objects.first().publish.address)
# print(Publish.objects.first().book_set.first().price) 里面列表不能用索引
多对多
# book=Book.objects.filter()[0]
# b2=Book.objects.filter()[2]
# a1=Author.objects.filter()[0]
# a2=Author.objects.last()
# book.author.add(a1)
# book.author.add(a2.id)
# b2.author.add(3,10)
# 清空
# book.author.clear()
# 通过id或对象清除author属性某个
# book.author.remove(a2)
# 清除该本书的之前所有关系记录,添加新的关系
# book.author.clear()
# book.author.add(a2.id)
# 去除列表中不存在的值,添加新值
# book.author.set([a1,a2])
查询
# 多对多
# print(Book.objects.last().author.first().name)
# print(Author.objects.last().book_set.last().name)
查询
__可以将关联的表关联表的属性全部调出来
查询出版社在上海的出版过的所有书的 作者姓名、作者电话、具体出版社名 的相关信息
print(Publish.objects.filter(address__5exact=‘上海‘).values(‘book__author__name‘,‘book__author__author_detail__telephone‘,‘name‘))
以上是关于基于表关系的增删改查的主要内容,如果未能解决你的问题,请参考以下文章