简体   繁体   English

将 Django 查询集转换为列表或字典

[英]Convert Django Queryset to list or dict

From my views.py I doing this query:从我的 views.py 我做这个查询:

var_query = DB.objects.filter(Q(user_id=str(request.user.id)) & Q(router_name='router1'  )).values('router_type',  'router_ip')

Working because I get this result:工作是因为我得到了这个结果:

{'router1': set(['[{"router_type": "CISCO", "router_ip": "192.168.1.1"}]'])}

the type of var_query is: <class 'django.db.models.query.QuerySet'> var_query 的类型是: <class 'django.db.models.query.QuerySet'>

When I convert this with list()当我用 list() 转换它时

converted = list(var_query)

and this error: AttributeError: 'set' object has no attribute 'iteritems'这个错误: AttributeError: 'set' object has no attribute 'iteritems'

becasue when a convert this queryset to list is inserted this: set(['因为当将此查询集转换为列表时插入此: set(['

How to convert to real list or dict so I can work with my key or value?如何转换为真正的列表或字典,以便我可以使用我的键或值?

It's not really clear what your final aim is.你的最终目标是什么还不是很清楚。 But it seems like you are overcomplicating things unnecessarily.但看起来你把事情不必要地复杂化了。 I would suggest simplifying your approach and just filter the queryset normally (note, it looks like these Q objects are also unnecessary here, you can just pass the args in directly).我建议简化您的方法,只需正常过滤查询集(注意,这里似乎也不需要这些Q对象,您可以直接传递参数)。

var_query = DB.objects.filter(
    Q(user_id=str(request.user.id)) & Q(router_name='router1')
)

The result will be a queryset object that implements the iterator protocol and can be iterated over normally like a list or list-like object.结果将是一个实现迭代器协议的查询集对象,并且可以像列表或类似列表的对象一样正常迭代。 Then to work with the fields in the data that you seem to be interested in, you can just do something like:然后要处理您似乎感兴趣的数据中的字段,您可以执行以下操作:

var_query = DB.objects.filter(
    Q(user_id=str(request.user.id)) & Q(router_name='router1')
)

for obj in var_query:
    router_type = obj.router_type
    router_ip = obj.router_ip
    # ... do other stuff with your data.

You don't need to bother using values unless you really have a proper use case for it.除非您确实有合适的用例,否则您无需费心使用values

If you can supply more context we can refine a more accurate solution.如果您可以提供更多上下文,我们可以改进更准确的解决方案。

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

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