Using Django JSON serializer for object that is not a Model - python

Is it possible to use Django serializer without a Model?
How it is done?
Will it work with google-app-engine?
I don't use Django framework, but since it is available, I would want to use its resources here and there.
Here is the code I tried:
from django.core import serializers
obj = {'a':42,'q':'meaning of life'}
serialised = serializers.serialize('json', obj)
this generates an error
ERROR ... __init__.py:385] 'str' object has no attribute '_meta'

Serializers are only for models. Instead you can use simplejson bundled with Django.
from django.utils import simplejson
json_str = simplejson.dumps(my_object)
Simplejson 2.0.9 docs are here.

The GQLEncoder class in this library can take a db.Model entity and serialize it. I'm not sure if this is what you're looking for, but it's been useful to me.

Related

How to deserialize a django model object?

I am fairly new to python and transitioning from Java, so I'll use the Java terminologies as I need to know the equivalent python version of it.
So I have a Django model as described below:
class Order(models.Model) :
order_id = models.TextField(null=False, blank=False)
is_completed = models.BooleanField(null=False, blank=False, default=False)
Also I have a kafka broker to process these orders. To push these into a kafka queue, I am transforming them into JSON objects as depicted below:
from django.core import serializers
serialized_obj = serializers.serialize('json', [order])
print("Pushing to kafka topic ", "some_topic")
print(serialized_obj)
send_message("some_topic", serialized_obj)
Now I need this JSON object to be converted back to Django model object, in Java we have something called as Jackson which could have done the same for me, but I am not sure how to do this in Python3.
I tried the below code snippet, it returned me an object of type <generator object Deserializer at 0x7fe000323bf8>
# consumer.py
try:
print(json.loads(msg.value()))
print("---------------------------------")
obj = serializers.deserialize("json", msg.value())
print(obj)
except Exception as e:
import traceback
print(traceback.format_exc())
How can I achieve this in Python3?
First to serialize the object do this:
from django.core import serializers
d = serializers.serialize('json', Order.objects.all()) # serialize all the objects in Order model
To deserialize the object from it
for obj in serializers.deserialize('json', d):
print(obj.object) ## return the django model class object
serializers.deserialize() gives an Deserializedobject
To get more details refer Django object deserialization

Type Error: is not JSON serializable

I`m trying to pass database objects from one view to another view. But when I try to achieve this using SESSION, I am getting this "is not JSON serializiable" error.
My Views.py:
def index(request):
listset = TheaterBase.objects.all()
request.session['s_listset'] = listset
def otherview(request):
result = request.session.get('s_listset')
How to pass the Database objects in between the views?
Thanks in advance
Server sessions can store JSON objects only. You are trying to store a complex Django QuerySet object, which naturally is not JSON serializable.
And trust me, even if it was, you wouldn't want to do this. It's not healthy to abuse your server's session with a high amount of data.
Let's just assume that your TheaterBase class is something like below(pseudo code)
class TheaterBase:
field1 ...
fielld2 ...
-------
# a method to produce json serializable representation
def as_dict(self):
return {'field1': self.field1, 'fileld2': self.fielld2}
Then on you view do
listset = [x.as_dict() for x in TheaterBase.objects.all()]
The issue here is the object coming out of your db query are not json serializable. The as_dict method above is constructing a json serializable representation of that object.
You can try using django serializers
from django.core import serializers
listset = serializers.serialize("json", TheaterBase.objects.all())

Class-based view "has no attribute .as_view()" error

I'm following this tutorial, trying to make an API for my Products table.
Here's my .views/API/apitest.py view:
from my_app.views.API.serializers import ProductSerializer
from my_app.models import Product
from rest_framework import generics
class APITest(generics.ListAPIView):
model=Product
serializer_class=ProductSerializer
queryset = Product.objects.all()
The urls.py entry:
url(r'^API/products/$', views.API.apitest.as_view(), name='apitest')
That line gives an error: 'module' object has no attribute 'as_view'. I'm just trying to create a simple example for the moment, so there's no need for decorators. What causes this error? I'm using Django 1.9.2.
apitest is the module, you need to use as_view on the class
url(r'^API/products/$', views.API.apitest.APITest.as_view(), name='apitest')
Although it may be better to look into your imports
from myapp.views.API.apitest import APITest
url(r'^API/products/$', APITest.as_view(), name='apitest')

How to serialize Django queryset.values() into json?

I have a model that has many fields, however for this problem I only need 3 of those fields. When I try to serialize a .values set I get an exception:
'dict' object has no attribute '_meta'
This is my code:
queryset = myModel.objects.filter(foo_icontains=bar).values('f1', 'f2', 'f3')
serialized_q = serializers.serialize('json', queryset, ensure_ascii=False)
As other people have said, Django's serializers can't handle a ValuesQuerySet. However, you can serialize by using a standard json.dumps() and transforming your ValuesQuerySet to a list by using list(). If your set includes Django fields such as Decimals, you will need to pass in DjangoJSONEncoder. Thus:
import json
from django.core.serializers.json import DjangoJSONEncoder
queryset = myModel.objects.filter(foo_icontains=bar).values('f1', 'f2', 'f3')
serialized_q = json.dumps(list(queryset), cls=DjangoJSONEncoder)
Django serializers can only serialize queryset, values() does not return queryset rather ValuesQuerySet object. So, avoid using values(). Rather, specifiy the fields you wish to use in values(), in the serialize method as follows:
Look at this SO question for example
objectQuerySet = ConventionCard.objects.filter(ownerUser = user)
data = serializers.serialize('json', list(objectQuerySet), fields=('fileName','id'))
Instead of using objectQuerySet.values('fileName','id'), specify those fields using the fields parameter of serializers.serialize() as shown above.
Make list from objectQuerySet:
data_ready_for_json = list( ConventionCard.objects.filter(ownerUser = user).values('fileName','id') )
My solution, It's work fine
from django.core.serializers import serialize
import json
permission_list = Permission.objects.all().order_by('-id')
permission_serialize= json.loads(serialize('json', permission_list))
return JsonResponse({'data': permission_serialize})
Just cast to dict every item and create json with json.dumps:
json.dumps([dict(item) for item in SomeModel.objects.all().values('id', 'title')])
Try this:
queryset = myModel.objects.filter(foo_icontains=bar)
serialized_q = serializers.serialize(queryset, many = True)

Django serializer for one object

I'm trying to figure out a way to serialize some Django model object to JSON format, something like:
j = Job.objects.get(pk=1)
##############################################
#a way to get the JSON for that j variable???
##############################################
I don't want:
from django.core import serializers
serializers.serialize('json', Job.objects.get(pk=1),ensure_ascii=False)
Because it returns JSON array, not a single object representation.
Any ideas?
One way I'm thinking of: is to find a way to get a hash(attribute,value) of the object and then use simplejson to get the JSON representation of it, however I don't know how to get that hash.
How about just massaging what you get back from serializers.serialize? It is not that hard to trim off the square brackets from the front and back of the result.
job = Job.objects.get(pk=1)
array_result = serializers.serialize('json', [job], ensure_ascii=False)
just_object_result = array_result[1:-1]
Not a fancy answer but it will give you just the object in json notation.
Method-1
Use Django Serializer with python format
from django.core import serializers
j = Job.objects.get(pk=1)
response = serializers.serialize('python', [j], ensure_ascii=False)
Method-2
use json format while serializing and loads the string response
import json
from django.core import serializers
j = Job.objects.get(pk=1)
json_str_response = serializers.serialize('json', [j], ensure_ascii=False)
response = json.loads(json_str_response)[0]
Method-3
Use Django REST Framework's Serializer class
define a serializer class and serialize the instance as
from rest_framework import serializers
class JobSerializer(serializers.ModelSerializer):
class Meta:
model = Job
fields = '__all__'
j = Job.objects.get(pk=1)
response = JobSerializer(instance=j).data
Reference
1. Serializer Django model object
I would suggest using Django's model_to_dict. If I'm not mistaken, serializers.serialize() relies on it, too, but it only works for list, not single model instance. That's how you get a dict instance with your model fields out of a single model:
from django.forms.models import model_to_dict
# assuming obj is your model instance
dict_obj = model_to_dict( obj )
You now just need one straight json.dumps call:
import json
json.dumps(dict_obj)

Categories