简体   繁体   中英

Convert Django Queryset to list or dict

From my views.py I doing this query:

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'>

When I convert this with list()

converted = list(var_query)

and this error: AttributeError: 'set' object has no attribute 'iteritems'

becasue when a convert this queryset to list is inserted this: 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).

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.

If you can supply more context we can refine a more accurate solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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