环境准备:
表结构
from django.db import models # Create your models here. class Publisher(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=32) class Book(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=32) publisher = models.ForeignKey('Publisher', related_name='person_book', related_query_name='ooxx')
表数据
# Book表 id title pubtime person_id 1 书1 1533225600000 1 2 书2 1533225600000 1 3 书3 1534435200000 1 4 书4 1535644800000 2 5 书5 1535126400000 2
id name 1 出版社1 2 出版社2 3 出版社3
执行过程:
当反向查询的时候,通过Publisher表查询Book表数据。
publishers = Publisher.objects.all() # 获取说有的出版社对象 for publisher in publishers: # 循环每一个出版社
p_id = publisher.id # 取到这个出版社的id
books = Book.objects.filter(publishet_id=p_id).all() # 取到这个出版社出版的所有书籍
print(books[0].id) # 打印第一本书的id
异常情况:
list index out of range 提示index超出范围。
当p_id=3的时候,查询不到对象,就不会报错。
结束!