简体   繁体   中英

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>

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.

there is exception:

if your object doesnt exist in db yet

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM