How to determine which fields were deferred / only in a Django request set

I am trying to serialize a request in json using my custom iterator. On models, I discover the fields in the model and insert them into a JSON dict, as I need them.

I find it difficult to figure out how to determine which fields were deferred in the model using the deferred or just query function.

Is there a way and how to determine which fields are pending and how to skip them?

+4
source share
3 answers

A few buried ...

queryset.query.get_loaded_field_names ()

+7
source

Here's how you can check if it is pending for the actual instance of the model:

from django.db.models.query_utils import DeferredAttribute for field in model_istance._meta.concrete_fields: if not isinstance(model_instance.__class__.__dict__.get(field.attname), DeferredAttribute): # insert in json dict or whatever need to be done .... 

Thus, it will not load this field from db. This implementation is actually taken from django. https://github.com/django/django/blob/master/django/db/models/base.py#L415

+6
source

The current version of Django (1.9) has a method for all instances of the model: instance.get_deferred_fields()

This seems to be the “official” implementation of Alexey’s answer.

+4
source

Source: https://habr.com/ru/post/1333253/


All Articles