Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get primary key of a deserialized object in Django

I have a list of objects stored in session (to pass the list from one view to another) [okay, there has to be a better way of doing this but this is a question for another time!]

I access the list from the session by doing:

object_list = request.session.get('object_list', None)

But this object_list is actually a serialized django object.

What i need is to now get all the pk of this object_list (to then rebuild a clean queryset...)

I tried this (deserializing then getting pk)

object_list_id=[]
for obj in serializers.deserialize("json", object_list):
            object_list_id.append(obj.pk)

but it doesn't seem to work.. any ideas ?

'DeserializedObject' object has no attribute 'pk'

PS: if i debug the obj from the loop, this is the object type:

{<DeserializedObject: riskass.Rating(pk=7)>}
like image 737
Malcoolm Avatar asked Dec 19 '22 08:12

Malcoolm


1 Answers

Got it, it doesn't say anything on this aspect in the documentation !

How to get the pk of a serialized object in django:

# filtered_ratings : list of serialized objects (serialized through django's serializer)

from django.core import serializers

for obj in serializers.deserialize("json", filtered_ratings):
    pk = obj.object.pk

Hope this helps someone someday !

like image 60
Malcoolm Avatar answered Dec 21 '22 09:12

Malcoolm