先看模型:
大的分類(主表)
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表中的馬列主義