码迷,mamicode.com
首页 > 其他好文 > 详细

查询相关

时间:2019-11-29 00:35:17      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:more   ==   报错   contains   when   对象   属性   lis   nta   

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

查询相关

标签:more   ==   报错   contains   when   对象   属性   lis   nta   

原文地址:https://www.cnblogs.com/realadmin/p/11954808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!