我是Python的新手,所以对我很轻松。我正在Django中编写一个AJAX处理程序。到目前为止,一切都非常直截了当。一天中的大部分时间里,我一直在反对这一点。我想返回一个包含一个包含查询集的字典的JSON字符串:
#
# models.py
#
class Project(models.Model):
unique_name = models.CharField(max_length=32, unique=True)
title = models.CharField(max_length=255, blank=True)
description = models.TextField('project description', blank=True)
project_date = models.DateField('Project completion date')
published = models.BooleanField()
class ProjectImage(models.Model):
project = models.ForeignKey('Project', related_name='images')
image = models.ImageField(upload_to=get_image_path)
title = models.CharField(max_length=255)
sort_metric = models.IntegerField()
#
# views.py
#
...
projects = Project.Project.objects.filter(published=True)
...
response_dict({
'success' : True,
'maxGroups' : 5, # the result of some analysis on the projects queryset
'projects' : projects
});
# This one works if I remove 'projects' from the dict
# response = json.dumps( response_dict )
# This one works only on projects
# response = serializers.serialize( 'json', response_dict, relations=('images') )
return HttpResponse( response, mimetype='application/javascript' )
我已经注释掉了两个序列化行,因为:
[<Project: Project object>] is not JSON serializable
'str' object has no attribute '_meta'
。请注意,我正在使用wadofstuff序列化程序,并了解它将解析我的模型中定义的OneToMany关系。但即使我只通过序列化projects
来实现这一点,我的输出中也没有任何ProjectImages。问题1:序列化整个response_dict
的最佳方法是什么?当然,我不是第一个想要这样做的人,对吗?
问题2:为什么我无法使ManyToOne关系起作用?
非常感谢你的帮助。
更新:刚发现这个:Django JSON Serialization with Mixed Django models and a Dictionary看起来很有希望,但我得到'QuerySet' object has no attribute '_meta'
=(
答案 0 :(得分:1)
你无法像这样序列化python对象。 django文档中有一节介绍如何操作。
https://docs.djangoproject.com/en/dev/topics/serialization/#id2
以下是关键部分:
json_serializer.serialize(queryset, ensure_ascii=False, stream=response)