Django的多表查询
假设有模型
class Category(models.Model):
id = models.CharField(primary_key = True,max_length = 255)
type_name = models.CharField(max_length = 255)
def __str__(self):
return self.id+"."+self.type_name
class Meta:
db_table = "category"
class BookList(models.Model):
name = models.CharField(primary_key = True,max_length = 255) #书名
author = models.CharField(max_length = 255) #作者
read_num = models.CharField(max_length = 255) #阅读人数
book_type = models.ForeignKey(Category, models.DO_NOTHING) #外键 ,书的类别
class Meta:
db_table = "booklist"
- 正向查询就是查询对象的主体是Category,要查询Category模型对应表里的数据
- 反向查询就是查询对象的主体是Category,要查询的是BookList里的数据
正向查找
t = models.Category.objects.filter()
>>> <QuerySet [<Category: 1.玄幻魔法>, <Category: 2.武侠修真>,
<Category: 3.都市言情>, <Category: 4.历史穿越>, <Category: 5.恐怖悬疑>,
<Category: 6.游戏竞技>,
<Category: 7.军事科幻>, <Category: 8.女生频道>]>
反向查找
t[0].booklist_set.values("name")
>>> <QuerySet [{'name': '七世悟道'}, {'name': '关于在异界求生这件小事'}, {'name': '刀镇星河'}, {'name': '变身之女侠时代'}, {'name': '吾名丹尊万木'}, {'name':
'基因贩卖商'}, {'name': '天地霸体诀'}, {'name': '天革'}, {'name': '天骄狂尊'}, {'name': '太古魂帝'}, {'name': '守域奇缘'}, {'name': '悲剧发生前[快穿]'}, {'name': '我有一张沾沾卡'}, {'name': '我的绝美御姐老婆'}, {'name': '我的美女俏老婆'}, {'name': '我的铆钢蒸汽时代'}, {'name': '战道天图'}, {'name': '无敌从满级属性开始'}, {'name': '极品朋友圈'}, {'name': '残魄御天'}, '...(remaining elements truncated)...']>.
#t = model.Category.objects.select_related("type_name").values("name")