[Django]-Can django lazy-load fields in a model?

20πŸ‘

βœ…

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!

9πŸ‘

There are two options for lazy-loading in Django: https://docs.djangoproject.com/en/1.6/ref/models/querysets/#django.db.models.query.QuerySet.only

  • defer(*fields)

    Avoid loading those fields that require expensive processing to convert them to Python objects.

    Entry.objects.defer("text")

  • only(*fields)

    Only load the fields that you actually need

    Person.objects.only("name")

    Personally, I think only is better than defer since the code is not only easier to understand, but also more maintainable in the long run.

πŸ‘€Mingyu

7πŸ‘

For something like this you can just override the default manager. Usually, it’s not advised but for a defer() it makes sense:

    class CustomManager(models.Manager):
        def get_queryset(self):
            return super(CustomManager, self).get_queryset().defer('YOUR_TEXTFIELD_FIELDNAME')

    class DjangoModel(models.Model):
        objects = CustomerManager()
πŸ‘€Marlon Bailey

Leave a comment