Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can django lazy-load fields in a model?

One of my django models has a large TextField which I often don't need to use. Is there a way to tell django to "lazy-load" this field? i.e. not to bother pulling it from the database unless I explicitly ask for it. I'm wasting a lot of memory and bandwidth pulling this TextField into python every time I refer to these objects.

The alternative would be to create a new table for the contents of this field, but I'd rather avoid that complexity if I can.

like image 506
Leopd Avatar asked Jun 16 '10 23:06

Leopd


People also ask

What is lazy loading in Django?

Lazy loading means that until you perform certain actions on the queryset, such as iterating over it, the corresponding DB query won't be made. Caching means that if you re-use the same queryset, multiple DB queries won't be made.

Why Django Querysets are lazy?

This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.

Is there a list field for Django models?

The most important part of a model and the only required part of a model is the list of database fields it defines. Fields are specified by class attributes. Be careful not to choose field names that conflict with the models API like clean, save, or delete.

What is timestamped model in Django?

TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.


1 Answers

The functionality happens when you make the query, using the defer() statement, instead of in the model definition. Check it out here in the docs: http://docs.djangoproject.com/en/dev/ref/models/querysets/#defer

Now, actually, your alternative solution of refactoring and pulling the data into another table is a really good solution. Some people would say that the need to lazy load fields means there is a design flaw, and the data should have been modeled differently.

Either way works, though!

like image 194
Alan Christopher Thomas Avatar answered Sep 28 '22 19:09

Alan Christopher Thomas