我在Django中有两个模型,我从中获得Json输出:
模型(简体)
class ServiceSubCategory(models.Model):
service_category = models.ForeignKey(ServiceCategory)
name_fa = models.CharField(default='', max_length=200)
name_en = models.CharField(default='', max_length=200)
def __unicode__(self):
return self.service_category.name_fa+' -> '+ self.name_fa
class Service(models.Model):
service_sub_category = models.ForeignKey(ServiceSubCategory)
img_fa = models.ImageField(default='img/default_service.png',upload_to='img/service/')
caption_fa = models.CharField(default='',max_length=200)
caption_en = models.CharField(default='',max_length=200)
def as_json(self):
return {
'id': self.id,
'caption_fa': self.caption_fa,
'caption_en': self.caption_en,
'img_fa': unicode(self.img_fa),
}
我想获得第一个模型主键值并将其与我从第二个模型获得的JSON合并:
我从ServiceSubCategory获取此JSON:
[1,2,3,4,5,6,7,8,9,10]
运行此代码:
idJson=json.dumps(list(ServiceSubCategory.objects.values_list('id',flat=True)))
得到这个Json:
[{"caption_fa": "some value", "caption_en": "something", "id": 2, "img_fa": "img/default_service.png"},
{"caption_fa": "somthing", "caption_en": "somthing", "id": 1, "img_fa": "img/service/IMAG0099_1H3sdjX.jpg"}]
通过这个
cat = ServiceSubCategory.objects.get(id=1)
dictionary=[obj.as_json() for obj in Service.objects.filter(service_sub_category=cat)]
我想要的是合并这两个JSons来得到这样的东西:
[["1":{"caption_fa": "some value", "caption_en": "something", "id": 2, "img_fa": "img/default_service.png"},
{"caption_fa": "somthing", "caption_en": "somthing", "id": 1, "img_fa": "img/service/IMAG0099_1H3sdjX.jpg"}],
["2":{"caption_fa": "some value", "caption_en": "something", "id": 3, "img_fa": "img/default_service.png"},
{"caption_fa": "somthing", "caption_en": "somthing", "id": 4, "img_fa": "img/service/IMAG0099_1H3sdjX.jpg"}]]
这就是我尝试这样做的方式:
def service(request):
idList=ServiceSubCategory.objects.values_list('id',flat=True)
idJson=json.dumps(list(ServiceSubCategory.objects.values_list('id',flat=True)))
for i in idList:
dictionary=[obj.as_json() for obj in Service.objects.filter(service_sub_category=i)]
idJson[i].append(dictionary) #Error
return HttpResponse(idJson, content_type='application/json')
我在idJson[i].append(dictionary)
收到错误:
'str'对象没有属性'append'
我真的不知道该怎么做。任何帮助将不胜感激。
答案 0 :(得分:0)
您似乎有一个字典列表和一个键列表,并希望使用第二个列表中的键创建字典字典。 这是一个简单的例子(假设你的列表长度相同):
ids = [1, 2, 3, 4]
dicts = [{'a':'b'}, {'c':'d'}, {'e':'f'}, {'g':'h'}]
dict_of_dicts = {i:d for i, d in zip(ids, dicts)}
print dict_of_dicts
#{1: {'a': 'b'}, 2: {'c': 'd'}, 3: {'e': 'f'}, 4: {'g': 'h'}}
答案 1 :(得分:0)
因此,在您当前的定义中存在以下问题:
idJson=json.dumps(list(ServiceSubCategory.objects.values_list('id',flat=True)))
返回一个数组,但你希望这是我理解的新dict,所以用
替换它idJson={i:[] for i in list(ServiceSubCategory.objects.values_list('id',flat=True))}
尽管公平地实施绿狼的建议看起来更适合程序的优雅
编辑** 你的最终结果应该是这样的:
def service(request):
idList = list(ServiceSubCategory.objects.values_list('id',flat=True))
idJson = {i:[] for i in idList}
for i in idJson:
cat = ServiceSubCategory.objects.get(id=i)
dictionary=[obj.as_json() for obj in Service.objects.filter(service_sub_category=cat)]
idJson[i].append(dictionary)
return HttpResponse(idJson, content_type='application/json')
在您的示例中,您的数组有一个键:值对,然后是另一个没有键的字典。这是不允许的。数组可以包含任何对象,但只能将整数作为键。对于键:值对,dicts可以将任何可清除对象作为键,将任何其他类型作为值。所以您的选项要么是使用数组,其中索引号与项目ID直接相关:
[dict1,dict2,dict3, etc..]
其中dict(id)看起来像你的一个词:
{"caption_fa": "some value", "caption_en": "something", "id": 2, "img_fa": "img/default_service.png"}
它甚至可以是一个词典列表:
[[dict1,dict3],[dict2,dict4]]
或者你可以按照建议使用dicts:
{'1': [dict1,dict2], '2': [dict3,dict4]}
答案 2 :(得分:0)
因此,我将forst数组转换为字符串数组(["1","2","3",...]
)并使用zip
而不是两个JSON,我合并了两个数组,然后将其转换为JSON:< / p>
idArray='["1","2","3",...]'
dictionaries='[[{"caption_fa": "some value", "caption_en": "something", "id": 2},
{"caption_fa": "somthing", "caption_en": "somthing", "id": 1}],
[{"caption_fa": "some value", "caption_en": "something", "id": 3},
{"caption_fa": "somthing", "caption_en": "somthing", "id": 4}]]'
import json
theArray = dict(zip(idArray, dictionaries))
theJson = json.dumps(theArray )
结果是:
[["1":{"caption_fa": "some value", "caption_en": "something", "id": 2},
{"caption_fa": "somthing", "caption_en": "somthing", "id": 1}],
["2":{"caption_fa": "some value", "caption_en": "something", "id": 3},
{"caption_fa": "somthing", "caption_en": "somthing", "id": 4}]]