我无法在json中序列化此向后关系查询的结果。
我已经粘贴了json的结果 - 它基本上就是我想要的(控制哪些字段也很好)但它充满了转义字符串,我无法弄清楚它到底是什么我需要的以我选择的格式生成干净,有效的json。
有人可以指出我做错了吗?
#models.py
class Blog(models.Model):
title = models.CharField(max_length="150")
pub_date = models.DateTimeField('Date published', null=True, blank=True)
class BlogImage(models.Model):
image = models.ImageField(upload_to='img')
parent_blog = models.ForeignKey(Blog)
#views.py
q_set = Blog.objects.order_by('-pub_date').prefetch_related('blogimage_set')
items = list()
for q in q_set:
q_sub_set = q.blogimage_set.all()
serial_q_sub_set = serializers.serialize('json', q_sub_set)
item = {
'id':q.id,
'title':q.title,
'slideshow_imgs':serial_q_sub_set
}
items.append(item)
#dump repsonse to json
items = json.dumps(items)
print items
#resulting json..
[{"slideshow_imgs": "[{\"pk\": 5, \"model\": \"site.blogimage\", \"fields\": {\"blog\": 3, \"image_description\": \"\", \"image\": \"images/cat-9822.jpg\", \"image_title\": \"\", \"image_alt\": \"\"}},
{\"pk\": 6, \"model\": \"site.blogimage\", \"fields\": {\"blog\": 3, \"image_description\": \"\", \"image\": \"images/a_cat_2.jpg\", \"image_title\": \"\", \"image_alt\": \"\"}}]",
"id": 3, "title": "last"},
答案 0 :(得分:0)
我不得不处理这种事情,使用自然键Serialization帮了很多忙。 Doc Link:https://docs.djangoproject.com/en/dev/topics/serialization/#serialization-of-natural-keys
从文档中你应该做的事情如下:
>>> serializers.serialize('json', [book1, book2], indent=2,use_natural_foreign_keys=True, use_natural_primary_keys=True)