zoukankan      html  css  js  c++  java
  • 查询相关

    values_list("gender","id",flat=True) # 这样会报错,只能取一个字段

    'flat' is not valid when values_list is called with more than one field.

    另一张表通过related_name__属性名(外键所在表的属性)

    obj_values_list = AuthorInfo.objects.all().values_list("zuozhe__title",flat=True)
    print(list(obj_values_list))
    # ['小张的第一本书', '小张的第二本书', '小红的第一本书', '小红的第二本书']


    另一张表通过filter (related_name__属性名(外键所在表的属性)) 获取对象
    objs = AuthorInfo.objects.filter(zuozhe__title__icontains="一").all()
    for obj in objs:
    print(obj.name)

    通过id获取,只能获取单一对象,Author是另一张表,zuozhe是写在外键表中的related_name
    objs = AuthorInfo.objects.filter(zuozhe__id=2).values_list("zuozhe__price",flat=True)
    print(list(objs))
    # ['2']

    =========================
    status更新
    objs = AuthorInfo.objects.filter(zuozhe__id=3).first() # 这里的zuozhe__id 指的是外键所在表自身的id
    # objs = BookInfo.objects.filter(author=objs).values_list("price",flat=True) 这么写也可以
    objs = BookInfo.objects.filter(author__id=objs.id).values_list("price",flat=True)
    print(list(objs))
    # ['8', '9']


    =========================
    choice 替换 使用values_list 时无法替换
    gender_choice = {"male":"男", "female":"女"}
    objs = AuthorInfo.objects.all().values("id","name","gender","zuozhe__title")
    for i in objs:
    i["gender"] = gender_choice[i["gender"]]
    for i in objs:
    print(i)

    {'id': 1, 'name': '小张', 'gender': '男', 'zuozhe__title': '小张的第一本书'}
    {'id': 1, 'name': '小张', 'gender': '男', 'zuozhe__title': '小张的第二本书'}
    {'id': 2, 'name': '小红', 'gender': '女', 'zuozhe__title': '小红的第一本书'}
    {'id': 2, 'name': '小红', 'gender': '女', 'zuozhe__title': '小红的第二本书'}

  • 相关阅读:
    rpm 命令详解
    自动配置原理
    ssm框架整合
    单个库创建用户和权限
    Mysql5.7安装过程
    Eclipse和JDK版本以及位数对应关系
    DHCP服务器
    常用Dos命令
    八、Linux上常用网络操作
    数据库分区表(转)
  • 原文地址:https://www.cnblogs.com/realadmin/p/11954808.html
Copyright © 2011-2022 走看看