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': '小红的第二本书'}

  • 相关阅读:
    Web API系列之三 基本功能实现
    Web API系列之二WebApi基础框架搭建
    C# (类型、对象、线程栈和托管堆)在运行时的相互关系
    C# 命名空间和程序集
    C# new关键字和对象类型转换(双括号、is操作符、as操作符)
    Vue.js系列之四计算属性和观察者
    Vue.js系列之三模板语法
    C# 对象哈希码
    Class与Style绑定
    Koa学习笔记
  • 原文地址:https://www.cnblogs.com/realadmin/p/11954808.html
Copyright © 2011-2022 走看看