简体   繁体   English

Django:从查询集字典中获取一个键和值

[英]Django: Get one key and value from queryset dictionary

I have this query: item = Item.objects.filter(id=3)我有这个查询: item = Item.objects.filter(id=3)

It is returning a queryset with its the keys and values.它返回一个带有键和值的查询集。 Now I need to extract a particular value from the queryset, like this:现在我需要从查询集中提取特定值,如下所示:

item_name = item['name']

But it does not work.但它不起作用。 How can I achieve this?我怎样才能做到这一点? Send the most simple way if possible, please.请尽可能以最简单的方式发送。 Thanks!谢谢!

You have several wrong assumptions here. 您在这里有几个错误的假设。

A queryset is not a dict and does not have keys and values. 查询集不是字典,并且没有键和值。 It's a sequence of items, if anything most similar to a list. 它是一系列项目,如果最类似于列表的话。

I think what you want to do is to get a specific instance from the database, and access its fields. 认为您想要做的是从数据库中获取特定实例,并访问其字段。 To get one instance you use get , not filter , as filter will always give you a queryset even if there is only a single match. 要获取一个实例,请使用get而不是filter ,因为即使只有一个匹配项,filter也会始终为您提供一个查询集。 Then, from that instance, you use attribute access not dict lookup. 然后,从该实例中,使用属性访问而不是dict查找。 So: 所以:

item = Item.objects.get(id=3)
item_name = item.name

Here you can use the getattr function of python through which you can get your objective.在这里你可以使用 python 的 getattr function 通过它你可以得到你的目标。

getattr(item, 'name') getattr(项目,'名称')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM