Home > Mobile >  How to deserialize a serialized queryset in Django?
How to deserialize a serialized queryset in Django?

Time:11-17

views.py

def ipd_report_view(request):
    report=IpdReport.objects.all()
    myFilter=IpdFilters(request.POST, queryset=report)
    report=myFilter.qs
    total1=report.aggregate(Sum('realization__amount_received'))
    total2=report.aggregate(Sum('realization__deficit_or_surplus_amount'))
    rp=serializers.serialize('json', report)
    request.session['report']=rp
    context={'report': report, 'total1':total1, 'total2':total2, 'myFilter':myFilter}
    return render(request, 'account/ipdreport.html', context)

In another view function, I have to use the data in the session to be able to make the function export the data to an excel file.

I did rp=request.session['report'], but this object is a string object, so how do I go about converting this back to a queryset? Or is there any other way to achieve this?

CodePudding user response:

You just need to use the reverse method, deserialize,

Django Docs - Serialization, deserializing-data

In your case, it would be something like this,

// serializers.deserialize returns an iterator,
// but we know is just one element
obj = list(serializers.deserialize("json", request.session['report']))[0]
// obj is a DeserializedObject not the instance of the model
// to inspect the element just use the object property
rp = IpdReport.objects.get(pk=obj.object.pk)

CodePudding user response:

The question specifically asks about getting a QuerySet back so it's worth noting that calling serializers.deserialize (per @cabesuon's answer) will not do that - it returns a generator yielding DeserializedObject. If that's not good enough for your use-case you may want to reconstruct a QuerySet:

IpdReport.objects.filter(
    pk__in=map(
        lambda o: o.object.pk,
        serializers.deserialize("json", request.session["report"]),
    )
)
  • Related