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)
Related
This is my model.py
class Ont_Pruebas_Json(models.Model):
usuario_id = models.CharField(max_length=12)
data = jsonfield.JSONField()
def __str__(self):
return '{}'.format(self.usuario_id)
On data field I am storing this:
{u'1': {u'user': u'user1',u'mac': u"'00:00:00:00:00:01'"}, u'2': {u'user': u'user1',u'mac': u"'00:00:00:00:00:01'"}}
On my views.py
I am passing the query set this way:
context['context_json'] = Ont_Pruebas_Json.objects.all()
How can pass from the queryset to json format so I can choose for example from 1 the key mac and get the value: 00:00:00:00:00:01.
In general, you shouldn't store json data directly in the database. There are lots of potential problems doing this. For example, if data is missing you might not know because you didn't validate it.
You should first parse your data so that python can read it. If you are using Django Rest Framework(DRF) use a serializer.
However, I found serializers confusing at the start so if you want to parse a queryset do so do as shown below.
from .models import Ont_Pruebas_Json
import json
query = Ont_Pruebas_Json.objects.get(usuario_id ='some_user_id')
data = json.loads(str(query))
I am using django-filter v1.1.0 , django 1.11. I want a dynamic filter for a model. I have created filters.py which contains the respective config for model filters. This site tells that:
It will generate a Django Form with the search fields as well as
return the filtered QuerySet.
It here refers to SomeModelFilter function. I tried applying len and objects functions to it's object, but it returns
AttributeError: 'SomeModelFilter' object has no attribute 'len'
AttributeError: 'SomeModelFilter' object has no attribute 'objects'
I want to get the filtered content. It doesn't seem to be a QuerySet to me.
filters.py
from project_app.models import *
import django_filters
class SomeModelFilter(django_filters.FilterSet):
class Meta:
model = SomeModel
fields = ['field_a', 'field_b', 'field_c', 'field_d']
views.py
somemodel_list = SomeModel.objects.all()
somemodel_filter = SomeModelFilter(request.GET, queryset=somemodel_list)
print(len(somemodel_filter)) # This gives the first error
print(somemodel_filter.objects.all()) # This gives the second error
I want to get the filtered content, hopefully which is contained in somemodel_filter object.
The problem is in this line print(somemodel_filter.objects.all()). somemodel_filter is not model, it's filterset instance and since it's don't have objects attribute. To get filtered queryset use qs attribute, like this:
print(somemodel_filter.qs)
You can find example of filter usage here.
filtered_data = ExampleFilter(requet.Get, queryset=Example.objects.all())
to get the filtered queryset
filtered_queryset_data = filtered_data.qs
Use serializer to serialize the data. Use many=true since the its a list
serialized_data = ExampleSerializer(filtered_queryset_data, many=true).data
I am using django and trying to store the queryset in session variable
def wholelist(request):
hotelvar=request.POST.get('service_type')
city_list=Hotels.objects.filter(city_name__iexact=request.POST.get('searchabc'))
if not city_list:
hotel_list=Hotels.objects.all()
context={'hotel_list':hotel_list}
return render(request, 'polls/homepage.html',context)
pricemin=200
pricemax=800
request.session['hlist']=city_list
I am getting the following error:
[Hotels: ashoka, Hotels: abc] is not JSON serializable
I tried to convert into list and then store it
request.session['hlist']=list(city_list)
I am getting the following error:
'QuerySet' object has no attribute 'POST'
This is the model structure of hotels
class Hotels(models.Model):
def __str__(self):
return self.hotel_name
hotel_name=models.CharField(max_length=200)
photo=models.ImageField()
city_name=models.CharField(max_length=200)
Is there a way to store queryset in session variable?
For is not JSON serializable error you can serialize your models with django serializers as follows:
from django.core import serializers
hotel_list=Hotels.objects.all()
json_hotel = serializers.serialize('json', hotel_list)
context={'hotel_list':json_hotel}
You can't save QuerySet direct in Django session , u need to serialize it first then you will be able to save it in session.
Let me know if it working with you
Cheers
What I am understanding by your problem is that you want to store all the values returned in a queryset to be stored in the session variable of the request.
But you can not do that as those querysets will be nothing but the reference to the objects.
For if you want to store the values, what you can do is
import json
def wholelist(request):
hotelvar=request.POST.get('service_type')
city_list=Hotels.objects.filter(city_name__iexact=request.POST.get('searchabc'))
if not city_list:
hotel_list=Hotels.objects.all()
context={'hotel_list':hotel_list}
return render(request, 'polls/homepage.html',context)
pricemin=200
pricemax=800
city_list2 = []
city_list_for_session = city_list.values()#this will store the values of querylist to the session
for item in city_list_for_session:
data = {
'hotel':item['hotel'],
'city_name':item['city_name']}
city_list2.append(data)
request.session['hlist']=city_list2
The function .values() will get you a list of all the items with the value of each column in a dictionary.
So basically what you will be getting is a list of dictionary with the values of queryset.
Hope it helps.
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())
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)