168đź‘Ť
simplejson
and json
don’t work with django objects well.
Django’s built-in serializers can only serialize querysets filled with django objects:
data = serializers.serialize('json', self.get_queryset())
return HttpResponse(data, content_type="application/json")
In your case, self.get_queryset()
contains a mix of django objects and dicts inside.
One option is to get rid of model instances in the self.get_queryset()
and replace them with dicts using model_to_dict
:
from django.forms.models import model_to_dict
data = self.get_queryset()
for item in data:
item['product'] = model_to_dict(item['product'])
return HttpResponse(json.simplejson.dumps(data), mimetype="application/json")
122đź‘Ť
The easiest way is to use a JsonResponse.
For a queryset, you should pass a list of the the values
for that queryset, like so:
from django.http import JsonResponse
queryset = YourModel.objects.filter(some__filter="some value").values()
return JsonResponse({"models_to_return": list(queryset)})
- [Django]-Django's Double Underscore
- [Django]-How do I integrate Ajax with Django applications?
- [Django]-How to stop autopep8 not installed messages in Code
28đź‘Ť
I found that this can be done rather simple using the “.values” method, which also gives named fields:
result_list = list(my_queryset.values('first_named_field', 'second_named_field'))
return HttpResponse(json.dumps(result_list))
“list” must be used to get data as iterable, since the “value queryset” type is only a dict if picked up as an iterable.
Documentation: https://docs.djangoproject.com/en/1.7/ref/models/querysets/#values
- [Django]-Django test app error – Got an error creating the test database: permission denied to create database
- [Django]-What is the use of PYTHONUNBUFFERED in docker file?
- [Django]-Execute code when Django starts ONCE only?
26đź‘Ť
From version 1.9
Easier and official way of getting json
from django.http import JsonResponse
from django.forms.models import model_to_dict
return JsonResponse( model_to_dict(modelinstance) )
- [Django]-Django-celery: No result backend configured
- [Django]-Django REST Framework: adding additional field to ModelSerializer
- [Django]-Django-allauth: Linking multiple social accounts to a single user
14đź‘Ť
Another great way of solving it while using a model is by using the values()
function.
def returnResponse(date):
response = ScheduledDate.objects.filter(date__startswith=date).values()
return Response(response)
- [Django]-How to implement followers/following in Django
- [Django]-Django aggregate or annotate
- [Django]-Django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey"
13đź‘Ť
Our js-programmer asked me to return the exact JSON format data instead of a json-encoded string to her.
Below is the solution.(This will return an object that can be used/viewed straightly in the browser)
import json
from xxx.models import alert
from django.core import serializers
def test(request):
alert_list = alert.objects.all()
tmpJson = serializers.serialize("json",alert_list)
tmpObj = json.loads(tmpJson)
return HttpResponse(json.dumps(tmpObj))
- [Django]-Cross domain at axios
- [Django]-Django: How to check if the user left all fields blank (or to initial values)?
- [Django]-Filtering dropdown values in django admin
9đź‘Ť
First I added a to_dict method to my model ;
def to_dict(self):
return {"name": self.woo, "title": self.foo}
Then I have this;
class DjangoJSONEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, models.Model):
return obj.to_dict()
return JSONEncoder.default(self, obj)
dumps = curry(dumps, cls=DjangoJSONEncoder)
and at last use this class to serialize my queryset.
def render_to_response(self, context, **response_kwargs):
return HttpResponse(dumps(self.get_queryset()))
This works quite well
- [Django]-Using Cloudfront with Django S3Boto
- [Django]-Trying to migrate in Django 1.9 — strange SQL error "django.db.utils.OperationalError: near ")": syntax error"
- [Django]-Django 2 – How to register a user using email confirmation and CBVs?
1đź‘Ť
For Django Model, try:
users = User.objects.all()
return JsonResponse ({'data' : list(users)})
- [Django]-DatabaseError: current transaction is aborted, commands ignored until end of transaction block?
- [Django]-How to customize activate_url on django-allauth?
- [Django]-What is a "django backend"?
0đź‘Ť
You can use this for the Django model. Here we get rid of the wrapper because of safe=False
, without it there will be an error. But .values()
will return you the key->value
in a multidimensional array
views.py
from django.http import JsonResponse
users = User.objects.all().values()
return JsonResponse(list(users), safe=False)
- [Django]-Error: could not determine PostgreSQL version from '10.3' – Django on Heroku
- [Django]-How can I activate the unaccent extension on an already existing model
- [Django]-Auto-create primary key used when not defining a primary key type warning in Django