1

how do i serialize output of a query with select related into a json ? When i serialize data from query with select_related, the resultant json doesn't contain related field data.

Table schema.

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)

Query using 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)

The result of the response is

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

while the result suppose to be

[{
  "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"
    }] 
  }
}]

I changed the query using values instead of select related but i go this error

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)

Error:

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

I have tried some solutions found on stackoverflow too but i got errors during serializing

First method

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

and the type() of uinfo is

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

Error:

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

Second method:

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)

and the type() of uinfo returned is class

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

Error:

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   

I also tried to convert query output result into a dict(using https://djangosnippets.org/snippets/2670/ ) before serializing into json but i got the following error

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

Error:

in deep_dump_instance
   if (instance.__class__, instance.pk) in seen:
AttributeError: 'QuerySet' object has no attribute 'pk'
Niya
  • 364
  • 3
  • 10

1 Answers1

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]
Niya
  • 364
  • 3
  • 10