I have used below query to get result from particular table.
industries.py:
from demo.models import IndustryCat1
import datetime
from django.db.models import Q
class Industries:
@staticmethod
def getIndustries(indId):
"""
Get contacts from contact_list where invitor id is same as given owner_id.
Args:
user_id
Returns:
contact user object
"""
try:
return IndustryCat1.objects.filter()
except IndustryCat1.DoesNotExist:
return None
views.py:
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from models import IndustryCat1
from demo.core.persistence.Industries import *
from django.shortcuts import get_object_or_404, render, render_to_response
from django.core import serializers
import json
def index(request):
industry = Industries()
qs = serializers.serialize("json", industry.getIndustries(1))
return HttpResponse(qs)
#return render(request, 'demo/test/isndustries_catagories.html', context)
Where qs is returning:
[{
"model": "demo.industrycat1",
"pk": 1,
"fields": {
"name": "Division A: Agriculture, Forestry, And Fishing"
}
}, {
"model": "demo.industrycat1",
"pk": 2,
"fields": {
"name": "Division B: Mining"
}
}, {
"model": "demo.industrycat1",
"pk": 3,
"fields": {
"name": "Division C: Construction"
}
}, {
"model": "demo.industrycat1",
"pk": 4,
"fields": {
"name": "Division D: Manufacturing"
}
}]
I want to fetch values of "fields" index. If not possible then please suggest what else I can use instead of serialize to fetch values within object returned by query.
Thanks in advance.
Get all names with a list comprehension.
names = [record['fields']['name'] for record in qs]
Get all fields
with a list comprehension.
fields = [record['fields'] for record in qs]
Using list comprehension:
data = [
{
"model": "demo.industrycat1",
"pk": 1,
"fields": {
"name": "Division A: Agriculture, Forestry, And Fishing"
}
},
{
"model": "demo.industrycat1",
"pk": 2,
"fields": {
"name": "Division B: Mining"
}
},
{
"model": "demo.industrycat1",
"pk": 3,
"fields": {
"name": "Division C: Construction"
}
},
{
"model": "demo.industrycat1",
"pk": 4,
"fields": {
"name": "Division D: Manufacturing"
}
}
]
print ([each_field["fields"]["name"] for each_field in data])
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.