Johan Cowé Johan Cowé - 4 years ago 119
Python Question

how can I store and read a Python list of Django model objects from and to the session?

I am looking for a way to put Django model objects into a list and then store this in the session. I found out that it requires serialization before it can be stored in the session. So when reading the list from the session I first serialize it.

But then I was hoping to be able to access my initial objects as before, but it turns out to be a DeserializedObject.

Does anyone know how I should approach my requirements ?
In a nutshell this is the code I was trying, yet unsuccessfully

team1_list = generate_random_playerlist() #generates a list of Player() objects
request.session['proposed_team_1'] = serializers.serialize('json', team1_list)

#some code inbetween

des_list = serializers.deserialize('json', request.session['proposed_team_1'])
for player in des_list :
print("name of player:"+player.last_name) #fails

Answer Source

I would not serialize the model instances themselves. Just write their primary keys to the session which is easy and requires no serialization. Then you can retrieve the queryset from the database in a single query and don't have to worry about changed data, missing instances and the like.

request.session['player_ids'] = list(players.values_list('pk', flat=True))

players = Player.objects.filter(pk__in=request.session.get('player_ids', []))

If your Player instances are not yet saved to the database, you might have to go your way. Then you get the actual model instance from the DeserializedObject via the .object attribute.

for player in des_list : 
    print("name of player:" + player.object.last_name)

See the docs on deserialization.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download