| | 378 | |
|---|
| | 379 | |
|---|
| | 380 | Pickling QuerySets |
|---|
| | 381 | ~~~~~~~~~~~~~~~~~~ |
|---|
| | 382 | |
|---|
| | 383 | If you pickle_ a ``QuerySet``, this will also force all the results to be |
|---|
| | 384 | loaded into memory prior to pickling. This is because pickling is usually used |
|---|
| | 385 | as a precursor to caching and when the cached queryset is reloaded, you want |
|---|
| | 386 | the results to already be present. This means that when you unpickle a |
|---|
| | 387 | ``QuerySet``, it contains the results at the moment it was pickled, rather |
|---|
| | 388 | than the results that are currently in the database. |
|---|
| | 389 | |
|---|
| | 390 | If you only want to pickle the necessary information to recreate the |
|---|
| | 391 | ``Queryset`` from the database at a later time, pickle the ``query`` attribute |
|---|
| | 392 | of the ``QuerySet``. You can then recreate the original ``QuerySet`` (without |
|---|
| | 393 | any results loaded) using some code like this:: |
|---|
| | 394 | |
|---|
| | 395 | >>> import pickle |
|---|
| | 396 | >>> query = pickle.loads(s) # Assuming 's' is the pickled string. |
|---|
| | 397 | >>> qs = MyModel.objects.all() |
|---|
| | 398 | >>> qs.query = query # Restore the original 'query'. |
|---|
| | 399 | |
|---|
| | 400 | .. _pickle: http://docs.python.org/lib/module-pickle.html |
|---|