Django连接查询
1、一对一查询
models.OneToOneField(Entry)
两个实体类:Author , Wife
1、通过 Author 找 Wife
author = Author.objects.get(id=1)
wife = author.wife
2、通过 Wife 找 Author
wife = Wife.objects.get(id=2)
author = wife.author
2、一对多/多对一
model = models.ForeignKey(Entry)
两个实体类:Publisher(一) , Book(多)
正向查询:
book = Book.objects.get(id=1)
publisher = book.publisher
反向查询
publisher = Publisher.objects.get(id=4)
books = publisher.book_set.all()
多对多查询
1、什么是多对多
A表中的一条记录可以与B表中的任意多条记录匹配,同时B表中的每一条记录也可以与A表中的任意多条记录相匹配
2、语法
entry = models.ManyToManyField(Entry)
3、查询
class Author(models.Model):
... ...
publish = models.ManyToManyField(Publish)
正向查询:在 Author 中查询 Publish
author = Author.objects.get(id=3)
pub_list=author.publish.all()
通过关联属性.all()
反向查询:在 Publisher 中查询 Author
pub = Publisher.objects.get(id=1)
auList = pub.author_set.all()