使用select_related到json的查询序列化数据结果

时间:2014-02-24 17:11:06

标签: json django python-2.7 serialization

如何将选择相关的查询的输出序列化为json? 当我使用select_related从查询序列化数据时,结果json不包含相关的字段数据。

表架构。

from django.db import models
class User(models.Model)
   username = models.CharField(max_length=30)
   first_name = models.CharField(max_length=30)
   last_name = models.CharField(max_length=30)
   email = models.CharField(max_length=50)

class Userinfo(models.Model)
   userId = models.oneToOneField(User)
   userImg = models.TextField()
   city = models.CharField(max_length=30)
   says = models.CharField(max_length=200)

使用select related

进行查询
 from django.core import serializers
 json_serializer = serializers.get_serialier("json")()
 uinfo = Userinfo.objects.filter(userId=1).select_related('userId')
 response = json_serializer.serialize(uinfo, ensure_ascii=False, indent=2, use_natural_keys=True)

回复的结果是

[{
  "pk": 1, 
  "model": "userinfo", 
  "fields": {
    "city": "mycity", 
    "says": "Hi, its me", 
    "userImg": "profile_img.png", 
    "userId": [ "user1" ] 
  }
}]

虽然结果假设是

[{
  "pk": 1, 
  "model": "userinfo", 
  "fields": {
    "city": "mycity", 
    "says": "Hi, its me", 
    "userImg": "profile_img.png", 
    "userId": [{ 
        "username" : "user1",
        "first_name" : "User",
        "last_name" : "ls1",
        "email" : "user1@host.com"
    }] 
  }
}]

我使用值而不是select相关更改了查询,但我发现此错误

uinfo = Userinfo.objects.filter(userId=1).values('userImg', 'city', 'says', 'userId__username', 'userId__first_name', 'userId__email')
response = json_serializer.serialize(uinfo, ensure_ascii=False, indent=2, use_natural_keys=True)

错误:

 concrete_model = obj._meta.concrete_model
 AttributeError: 'dict' object has no attribute '_meta'

我已经尝试了在stackoverflow上找到的一些解决方案但是在序列化期间我遇到了错误

第一种方法

from rest_framework.renderers import JSONRenderer
uinfo = Userinfo.objects.filter(userId=1).select_related('userId')
response = JSONRenderer().render(uinfo)

和uinfo的type()是

<class 'django.db.models.query.QuerySet'>

错误:

TypeError: [<Userinfo: Userinfo object>] is not JSON serializable

第二种方法:

from rest_framework.renderers import JSONRenderer
uinfo = Userinfo.objects.filter(userId=1).values('userImg', 'city', 'says', 'userId__username', 'userId__first_name')
response = JSONRenderer().render(uinfo)

返回的uinfo的type()是class

<'django.db.models.query.ValuesQuerySet>

错误:

TypeError: [{'userImg': u'profile_img.png', 'city': u'mycity', 'says' : u'Hi, its me' 'userId__username': u'user1', 'userId__first_name': u'user'}] is not JSON serializable   

在尝试序列化为json之前,我还尝试将查询输出结果转换为dict(使用https://djangosnippets.org/snippets/2670/)但是我收到了以下错误

uinfo = Userinfo.objects.filter(userId=1).select_related('userId')
uinfodata = deep_dump_instance(uinfo)

错误:

in deep_dump_instance
   if (instance.__class__, instance.pk) in seen:
AttributeError: 'QuerySet' object has no attribute 'pk'

1 个答案:

答案 0 :(得分:2)

views.py

 from django.utils import simplejson

 def convert_to_json():
   uinfo = Userinfo.objects.filter(userId_id__in=inner_qs).values('userId__username', 'userImg', 'says', 'userId__first_name', 'city')
   lusers = ValuesQuerySetToDict(users)
   response = simplejson.dumps(lusers)
   return response

 def ValuesQuerySetToDict(vqs):
   return [item for item in vqs]