简体   繁体   English

Python序列化(到JSON)问题

[英]Python Serialization (to JSON) issue

I'm a bit of a newbie in Python, so go easy on me. 我是Python的新手,所以对我很轻松。 I'm writing an AJAX handler in Django. 我正在Django中编写一个AJAX处理程序。 Everything's been pretty straight-forward on this until now. 到目前为止,一切都非常直截了当。 I've been banging my head against this bit for the better part of a day. 一天中的大部分时间里,我一直在反对这一点。 I'd like to return a JSON string that contains a dict that contains a queryset: 我想返回一个包含一个包含查询集的dict的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' )

I've commented out the two serialization lines, because: 我已经注释掉了两个序列化行,因为:

  1. The first one seems to only work with 'simple' dicts and since projects is included in my dict, it fails with [<Project: Project object>] is not JSON serializable 第一个似乎只适用于'简单'的dicts,因为项目包含在我的dict中,它失败了, [<Project: Project object>] is not JSON serializable
  2. The second one seems to only work with querysets/models and since the 'outer' part of my dict is non-model, it complains that 'str' object has no attribute '_meta' . 第二个似乎只适用于查询集/模型,因为我的dict的'外部'部分是非模型的,它抱怨'str' object has no attribute '_meta' Note that I am using the wadofstuff serializer with the understanding that it would resolve the OneToMany relationship as defined in my model. 请注意,我正在使用wadofstuff序列化程序,并了解它将解析我的模型中定义的OneToMany关系。 But even when I get this working by only serializing projects , I do not have any of my ProjectImages in the output. 但即使我只通过序列化projects来实现这一点,我的输出中也没有任何ProjectImages。

QUESTION 1: What is the best way to serialize the whole response_dict ? 问题1:序列化整个response_dict的最佳方法是什么? Surely, I'm not the first person to want to do this, right? 当然,我不是第一个想要这样做的人,对吧?

QUESTION 2: Why am I unable to get the ManyToOne relationship to work? 问题2:为什么我无法使ManyToOne关系起作用?

Many thanks for your help. 非常感谢您的帮助。

UPDATE: Just found this one: Django JSON Serialization with Mixed Django models and a Dictionary and it looked promising, but I get 'QuerySet' object has no attribute '_meta' =( 更新:刚刚找到这个: Django JSON序列化与混合Django模型和一个字典 ,它看起来很有前途,但我得到'QuerySet' object has no attribute '_meta' =(

You can't serialize a python object like that. 你无法像这样序列化python对象。 There is a section in the django documentation on what to do. django文档中有一节介绍如何操作。

https://docs.djangoproject.com/en/dev/topics/serialization/#id2 https://docs.djangoproject.com/en/dev/topics/serialization/#id2

Here is the key part to look at: 以下是关键部分:

json_serializer.serialize(queryset, ensure_ascii=False, stream=response)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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