user10332687
user10332687

Reputation:

Ignore one field in a django model

I have a django model that has the following four fields:

class File:
    id = models.PrimaryKey()
    name = models.CharField()
    is_active = models.BooleanField()
    data = models.JSONField()

The data field is massive, perhaps 5MB per entry. Is there a way I can hide that field when I do an ORM query without having to specify all the fields I want to view each time? Something like:

File.objects.all() # exclude data field
File.objects.values('id', 'data') # include the data field

Upvotes: 5

Views: 6947

Answers (2)

shafikshaon
shafikshaon

Reputation: 6414

In some complex data-modeling situations, your models might contain a lot of fields, some of which could contain a lot of data (for example, text fields), or require expensive processing to convert them to Python objects. If you are using the results of a queryset in some situation where you don’t know if you need those particular fields when you initially fetch the data, you can tell Django not to retrieve them from the database.

This is done by passing the names of the fields to not load to defer():

Entry.objects.defer("headline", "body")

Also mention that, Whenever you call only() it replaces the set of fields to load immediately. The method’s name is mnemonic: only those fields are loaded immediately; the remainder are deferred.

Upvotes: 2

Amine Messaoudi
Amine Messaoudi

Reputation: 2309

You can use only() to specify the fields you want

File.objects.only('id', 'data')

Upvotes: 2

Related Questions