mainstream

跨表查询

一、ORM 跨表查询

class Book(models.Model):

title = models.CharField(max_length=32)

publish = models.ForeignKey(to="Publish",to_field="id",on_delete=models.CASCADE)

authors = models.ManyToManyField(to = "Author",related_name=\'bookList\')



class Publish(models.Model):

name = models.CharField(max_length=32)



class Author(models.Model):

name = models.CharField(max_length=32)

ad = models.OneToOneField("AuthorDetail",on_delete=models.CASCADE)



class AuthorDetail(models.Model):

telephone = models.BigIntegerField()

  

1、基于对象查询(sql:子查询):

一对多、(Publish--Book)

正向查询,按字段:

查询python这本书的出版社所在名称

book_obj = Book.objects.filter(title="python").first()

print(book_obj.publish.name)

反向查询,按表明小写_set:

人民出版社出版过的所有书籍名称

publish_obj = Publish.objects.filter(name="人民出版社出版").first()

print(publish_obj.book_set.all())

for obj in publish_obj.book_set.all():

print(obj.title)	书名逐一显示

  

 

多对多、

正向查询,按字段:

python这本书所有作者的名字

book_obj = Book.objects.filter(title="python").first()

book_obj.authors.all()

反向查询,按表明小写_set:

alex出版过的所有书籍名称

alex = Author.objects.filter(name="alex").first()

方法一:alex.book_set.all()

方法二(这是设置related_name=\'bookList\'方法):alex.bookList.all()

  

一对一、

正向查询,按字段:

查询alex的手机号

alex = Author.objects.filter(name="alex").first()

alex.ad.telephone

反向查询,按表明小写:

以151开头的手机号的作者的名字

ad = AuthorDetail.objects.get(telephone__startswith="151")

ad.authour.name

  

2、基于Queryset和__(sql:join语句):

正向查询,按字段

反向查询,按表明小写


一对多、(Publish--Book)

正向查询,按字段:

查询python这本书的出版社所在名称

Book.objects.filter(title="python").values("publish__name")

for obj in Book.objects.filter(title="python"):

temp={}

temp["publish__name"] = obj.publish.name


反向查询,按表明小写:

人民出版社出版过的所有书籍名称

Publish.objects.filter(name="人民出版社出版").values("book__title")

 

 

多对多、

python这本书所有作者的名字

Book.objects.filter(title="python").values("authors__name")

 

alex出版过的所有书籍名称

Author.objects.filter(name="alex").values("book__title")
一对一、
正向查询,按字段:

查询alex的手机号

Author.objects.filter(name="alex").values("ad__telephone")

 

以151开头的手机号的作者的名字

AuthorDetail.objects.filter(telephone__startswith="151").values("author__name")  

 

三、拓展

eg1:
查询python这本书的出版社所在名称

Book.objects.filter(title="python").values("publish__name")

Publish.objects.filter(book__title="python").values("name")

eg2:
以151开头的手机号的作者的名字

AuthorDetail.objects.filter(telephone__startswith="151").values("author__name")

Book.objects.filter(authors__ad__telephone__startswith="151").values("title","publish__name")

  

 

分类:

技术点:

相关文章:

  • 2021-11-15
  • 2021-10-09
  • 2022-12-23
  • 2022-12-23
  • 2021-07-19
  • 2020-02-03
  • 2022-01-11
猜你喜欢
  • 2022-12-23
  • 2022-01-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-06
  • 2021-12-06
相关资源
相似解决方案