django:查询,反向查询

先看模型:

大的分类(主表)

class Category(models.Model):
name = models.CharField(max_length=20, null=True)

小的分类(子表)

class SmartCategory(models.Model):
name = models.CharField(max_length=20, null=True)
category = models.ForeignKey(Category, null=True)

查询

1、

  A

  如图就是查:category下的哲学对应smartcategory的世界哲学、古代哲学。。。

obj = Category.objects.get(id=10)
data = obj.smartcategory_set.all()
注意1、smartcategory_set为小写(首字母和中间的都要小写),
  2、obj是使用.get()获取的单一查询 ,使用filter(),excute()等获取的是查询集集合不能用此方法

 B

也可以在models建数据模型时添加参数(别名)
class SmartCategory(models.Model):
name = models.CharField(max_length=20, null=True)
category = models.ForeignKey(Category, null=True,related_name = "test")
使用以下方式查询
data = Category.objects.get(id=10).test.all()


2、
查询smartcategory中对应的字段和对应category结果
使用
SmartCategory.objects.get(pk=4).name
获取name字段,id=4时结果是诗词,
SmartCategory.objects.get(pk=4).category
获取id=4时对应的category_id=8对应category表中的马列主义
 
原文地址:https://www.cnblogs.com/liuda9495/p/8327936.html