41👍
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.
58👍
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]-How to register users in Django REST framework?
- [Django]-Django 1.8 – what's the difference between migrate and makemigrations?
- [Django]-Override existing Django Template Tags
25👍
Make list from objectQuerySet:
data_ready_for_json = list( ConventionCard.objects.filter(ownerUser = user).values('fileName','id') )
- [Django]-Django Count() in multiple annotations
- [Django]-Django create userprofile if does not exist
- [Django]-Unable to import path from django.urls
6👍
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})
- [Django]-Why does Django's render() function need the "request" argument?
- [Django]-ImageField overwrite image file with same name
- [Django]-How to move a model between two Django apps (Django 1.7)
2👍
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')])
- [Django]-How to stop celery worker process
- [Django]-WARNING: Running pip as the 'root' user
- [Django]-Easiest way to rename a model using Django/South?
0👍
Try this:
queryset = myModel.objects.filter(foo_icontains=bar)
serialized_q = serializers.serialize(queryset, many = True)
- [Django]-New url format in Django 1.9
- [Django]-Django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey"
- [Django]-Accepting email address as username in Django