Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46178

Django - Is storing objects in session a good practice?

class Book(models.Model):
  author = models.ForeignKey(User)
  name = models.CharField(max_length=100)

def view(request):
  book = Book.objects.get(pk=1)
  request.session['selected_book'] = book

Is it a good practice to store Objects in Session instead of their id ?
Will it be "picklable" enough to be used in templates for example ?

<div>{{ request.session.book.author.name }}</div>

Upvotes: 14

Views: 9396

Answers (2)

Sławomir Lenart
Sławomir Lenart

Reputation: 8377

there is exception:

if your object doesnt exist in db yet

for example if you build it (object) through many steps/views.

Upvotes: 4

Daniel Roseman
Daniel Roseman

Reputation: 599580

This seems like a bad idea. Apart from anything else, if you store an object in the session, it won't change if/when the database version does.

Upvotes: 23

Related Questions