Brian Obot
Brian Obot

Reputation: 418

Using a Deserialized Django Object Directly

I have found a lot of documentation about serializing a queryset in django, and i found out that to serialize a single object or instance of a model you simply needed to wrap that instance in a list '[]'. But here is my Issue, I serialized an object in one view passed it into session and deserialized said object in another view and it work just fine... but what i get is a python generator, how can i get the initial object without the generator?

view that i serialized the object

def sales_detail(request, pk=None):
    sales_object = Sales.objects.get(pk=pk)
    data = serializers.serialize('json', [sales_object])
    request.session['data'] = data
    return render(request, 'sales/detail.html', context)

view that i deserialized the object

def connect_page(request, item_type=None, item_id=None):
    data  = request.session.get('data', None)
    print("Serialized Obeject from Session: ", data[1:-1])
    clean_data = serializers.deserialize('json', data)
    print("Deserialized object from the session : ",  clean_data)
    ...
    return render(request, 'sales/connections.html', context)

Results for First Print

Serialized Obeject from Session:  {"model": "sales.request", "pk": 1, "fields": {"created": "2021-09-08T14:51:01.891Z", "updated": "2021-09-08T19:48:59.603Z", "description": "asa sja schsac  sjbca dcbl sdac dc ahclbkscj sadc sk c sclbsclbd cS LCzx", "unit_price": 0.0, "owner": 1, "active": false, "urgent_flag": false, "completed": false, "type": "request", "quantity": 1, "edited": true, "slug": "nfs-most-wanted-2005", "title": "NFS Most Wanted 2005", "image": "uploaded_products/default_request.png", "tags": [], "categories": [8, 9]}}

Results for Second Print

Deserialized object from the session :  <generator object Deserializer at 0x000001E220703D60>

I know i could just loop over the generator the collect the value...but it reducdant knowing this generator contains only one object ...i need direct access without looping

Upvotes: 1

Views: 870

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476813

Django will not eagerly deserialize, it works lazily: it will only deserialize if you need the items, for example to enumerate over it.

You can make a list of model objects by constructing a list:

clean_data = list(serializers.deserialize('json', data))

If you only wish to enumerate, you can simply leave it a generator, and enumerate over it in the template. Then the generator will deserialize the objects one-by-one, and thus emit these in the {% for … %} … {% endfor %} loop.

Upvotes: 1

Related Questions