Django MongoDB QuerySet 结果转换为 JSON
我有这些模型:
class Projects(models.Model):
projectName =models.CharField(max_length = 100,unique=True,db_index=True)
projectManager = EmbeddedModelField('Users')
class Users(models.Model):
name = models.CharField(max_length = 100,unique=True)
designation = models.CharField(max_length =100 )
我需要从我的视图中返回所有项目对象的 JSON,我尝试了 json.dumps(Projects.objects.all()) 但它不起作用,我如何完成它?
编辑: 我使用 json.dumps(Projects.objects.all().values()) 并得到了这个:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\Python27\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "D:\Python27\lib\json\encoder.py", line 203, in encode
chunks = list(chunks)
File "D:\Python27\lib\json\encoder.py", line 436, in _iterencode
o = _default(o)
File "D:\Python27\lib\json\encoder.py", line 178, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: [{'projectName': u'HELLO', 'projectManager': {u'id': u'4eb3b792b990a24e49f6bb26', u'name': u'anshul', u'designation': u'programmer', u'teams': []}, '
id': u'4eb3b7d0e814520db4000000'}] is not JSON serializable
现在我得到了我想要的结果,但为什么这也给了我错误。
I have these models:
class Projects(models.Model):
projectName =models.CharField(max_length = 100,unique=True,db_index=True)
projectManager = EmbeddedModelField('Users')
class Users(models.Model):
name = models.CharField(max_length = 100,unique=True)
designation = models.CharField(max_length =100 )
I need to return JSON from my view for all Projects objects,I tried json.dumps(Projects.objects.all()) but it did not worked,how do i accomplished it??
EDIT:
I used json.dumps(Projects.objects.all().values()) and got this:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\Python27\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "D:\Python27\lib\json\encoder.py", line 203, in encode
chunks = list(chunks)
File "D:\Python27\lib\json\encoder.py", line 436, in _iterencode
o = _default(o)
File "D:\Python27\lib\json\encoder.py", line 178, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: [{'projectName': u'HELLO', 'projectManager': {u'id': u'4eb3b792b990a24e49f6bb26', u'name': u'anshul', u'designation': u'programmer', u'teams': []}, '
id': u'4eb3b7d0e814520db4000000'}] is not JSON serializable
Now i am getting the result what i want but why is this giving me error as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试 Jason.dumps-ing Queryset.values()。
Try Jason.dumps-ing the result of Queryset.values().
查询集不可序列化。您可以尝试使用 list(self.objects) 而不是 self.objects 来强制将查询集作为列表进行处理。在你的情况下尝试这样的事情
Querysets are not serializable. You could try to use list(self.objects) instead self.objects to force the queryset to be processed as a list. In your case try something like this