Django ORM各种查询
正向和反向查询
正向 ----> 关联字段在当前表中,从当前表向外查叫正向
反向 —> 关联字段不在当前表中,当当前表向外查叫反向
正向通过字段,反向通过表名查
表结构
from django.db import models class Author(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() #主表 class Book(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField(max_length=32) price = models.IntegerField() #一对多字段 publish = models.ForeignKey('Publish', related_name='book', on_delete=models.CASCADE) #多对多字段 authors = models.ManyToManyField('Author',related_name='author_book')
class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32)
一对多 ForeignKey
book – > publish :一个出版社有多个书
正向:
1、基于字段:obj.(外键).属性
因为book表中有publish字段。所以正向查询书的出版社
book_obj = mdoels.Book.objects.filter(nid=1).first() book_obj.publish.name
反向:obj.(表名小写_set).all() 或者 obj. book (related_name='book') .all()
1、set查询
1 因为publish没有book字段。要查询关于book的内容,就需要做反向查询 2 3 publish_obj=models.Publish.objects.filter(nid=1).first() 4 books = publish_obj.book_set.all() #如果Book表中没有related_name=‘book’用这方式 5 books = publish_obj.book.all() #Book表中有related_name=‘book’ 6 for book in books: 7 print(book.title)
多对多 ManyToManyField
正向:
1、基于字段:obj.(外键).all()
1 book_obj = models.Book.objects.get(pk=1).first() 先拿到要查的对象 2 3 author = book_obj.authors.all() 查到这一本书关联的作者对象 4 5 for a in author: 6 print(a.name,a.age) 循环遍历作者对象,拿到作者的属性
反向:
obj.(表名小写_set).all() 或者 obj. author_book(related_name='author_book') .all()
1、set查询
#set查询 authorobj = models.Author.objects.filter(nid=1).first() books = authorobj.book_set.all() for book in books: print(book.title) #related_name查询方式 authorobj= models.Author.objects.filter(nid=1).first() books = authorobj.author_book.all() for book in books: print(book.title)