'How to tell which fields have been deferred/only'd in a Django queryset
I am trying to serialize a queryset into json using my custom iterator. On the models I detect the fields in the model and insert them into the JSON dict as I need them.
I am having trouble figuring out how to determine which fields have been deferred in the model using the defer or only queryset function.
Is there a way, and how, to find out which fields are deferred and how to skip over them?
Solution 1:[1]
Current version of Django (1.9) has a method on all model instances:
instance.get_deferred_fields()
This seems to be the "official" implementation of Alexey's answer.
Solution 2:[2]
Here is how you can check if it's deferred for an actual model instance:
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 ....
This way it will not load that field from db. This implementation is actually taken from django. https://github.com/django/django/blob/d818e0c9b2b88276cc499974f9eee893170bf0a8/django/db/models/base.py#L415
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SMX |
| Solution 2 | JayTurnr |
