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.
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))
With this code all of the values are specified to return a QuerySet
import json
posts = (Post.objects.filter(owner=authenticated_user)
.values('id', 'title', 'summary'))
json_posts = json.dumps(list(posts))
Is there a way to avoid specifying all of the values for the QuerySet ('id', 'title', and 'summary')? For example
posts = (Post.objects.filter(owner=authenticated_user)
.values(ALL VALUES))
EDIT:
Ultimately the goal is to serialize the QuerySet into JSON. The following code raises an AttributeError
try:
obj = SystemOverview.objects.filter(serial=pk).values()
except SystemOverview.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
return Response(serializers.serialize("json", list(obj)))
#ERROR MESSAGE
#AttributeError: 'dict' object has no attribute '_meta'
What is the correct way of serializing a Django object model into JSON without listing all of its values?
As stated in the Django Documentation https://docs.djangoproject.com/en/1.10/ref/models/querysets/#values
The values() method takes optional positional arguments, *fields,
which specify field names to which the SELECT should be limited. If
you specify the fields, each dictionary will contain only the field
keys/values for the fields you specify. If you don’t specify the
fields, each dictionary will contain a key and value for every field
in the database table.
Simply use Post.objects.filter(owner=authenticated_user).values()
EDIT:
objs = SystemOverview.objects.filter(serial=pk).values()
if request.method == 'GET':
return Response(serializers.serialize("json", objs))
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())
This is my model in Django.
class Meta_Columns(models.Model):
cur_parent=models.CharField(max_length=200)
cur_child=models.CharField(max_length=200)
cur_child_label=models.CharField(max_length=200)
cur_childisparent= models.BooleanField()
cur_childtype= models.CharField(max_length=200,choices=CHILD_TYPE)
cur_Misc= models.CharField(max_length=200,blank=True)
class Admin:
pass
I want to select the 'cur_parent' column and get the distinct values (from MySql)
Below is the code.
if request.method == 'POST':
all_parents = Meta_Columns.objects.only("cur_parent").distinct("cur_parent")
data = serializers.serialize("json", all_parents)
return HttpResponse(data, content_type='application/json')
If i make the call to the view, this is the error i get.
DISTINCT ON fields is not supported by this database backend
I cannot use values("field_name").distinct() because it will not work with json & this error is thrown : 'dict' object has no attribute '_meta'.
How to get distinct values then?
Django's serializers.serialize() expects Django model instances as inputs, and distinct() won't be returning that (even more so because cur_parent is not a ref to a model, but a CharField)
If .values('cur_parent') works for you, you can just serialize that list of distinct parents with a regular JSON serializer, e.g.
import json
all_parents = Meta_Columns.objects....values('cur_parent').distinct()
json_str = json.dumps(all_parents) # Works with regular data structure,
# doesn't need to be a Django model instance
return HttpResponse(json_str, content_type='application/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)