larsl
larsl

Reputation: 358

In Django, how do I serialize a QuerySet that returns a dict object (created with .values())

In Django 1.10 I am trying to serialize an QuerySet that I obtained from the following query:

events_in_period = Event.objects \
.filter(timestamp__gte=start_day,
        timestamp__lte=end_day,
        request__isnull=False,
        name=EventType.COMPLETED) \
.annotate(date=TruncDay('timestamp')) \
.values('date') \
.annotate(completed_count=Count('id')) \
.order_by('date')

The main thing is the .values() statement that makes this statement return a QuerySet that contains a dict rather than a Django model instance.

Therefore the following calls to serialize it

from django.core import serializers
output = serializers.serialize('json', result)

fail with the following error:

AttributeError: 'dict' object has no attribute '_meta'

Any suggestions on serialization without omitting the .values() as I need them for brevity.

Upvotes: 1

Views: 922

Answers (1)

zaidfazil
zaidfazil

Reputation: 9235

If you want to serialize the dict object into json, then you could import json,

import json
data = json.dumps(result)

The Django serializers are for Django model objects and QuerySets. That's why it's looking for a _meta field. 

Upvotes: 1

Related Questions