zoukankan      html  css  js  c++  java
  • 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表中的马列主义
     
  • 相关阅读:
    什么是web标准
    Axure 快捷方式
    asp.net mvc4中model与Model的区别
    Git 操作常用命令
    ASP.NET MVC 中@html.ActionLink的几种参数格式
    Datagridview控件实现分页功能
    winform 拖动无边框窗体(调用Windows API)
    利用C#轻松创建不规则窗体
    Linq to sql 操作
    第一篇博客,写些学习感想
  • 原文地址:https://www.cnblogs.com/liuda9495/p/8327936.html
Copyright © 2011-2022 走看看