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表中的马列主义
     
  • 相关阅读:
    8. String to Integer (atoi)
    PHP Warning: strftime(): It is not safe to rely on the system's timezone set
    Jackson 使用
    用vim去掉utf-8 BOM
    oracle 11g 从 dmp 文件中导出 sql 代码 的方法.
    git gitosis 添加项目
    Linux gcc和gdb程序调试用法 {转}
    Dos中转义符
    HTML样式链接到外部样式表
    转:财富与智慧
  • 原文地址:https://www.cnblogs.com/liuda9495/p/8327936.html
Copyright © 2011-2022 走看看