#31803 closed Cleanup/optimization (wontfix)

Should ModelState.field_cache be documented?

Reported by: Jaap Roes Owned by: nobody
Component: Documentation Version: 3.0
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


While writing a model method that relies on data of a related object I decided that it would be nice if this method could log a warning when it is called without the related object having been prefetched.

I came across this StackOverflow question https://stackoverflow.com/questions/36402129/is-there-a-way-to-check-whether-a-related-object-is-already-fetched and based on that I implemented something like the following:

def my_method(self):
    if 'related_object' not in self._state.fields_cache:
            'Calling MyModel.my_method without prefetching the related object can inefficient '
            'Consider adding prefetch_related/select_related to the originating queryset.',

This seems to work as intended.

Checking the docs I see that Model._state is documented (https://docs.djangoproject.com/en/3.0/ref/models/instances/#state), but the fields_cache attribute isn't.

Can I rely on fields_cache? Should I consider it to be public but undocumented, or private with the possibility of disappearing without notice?

Change History (2)

comment:1 Changed 14 months ago by Jaap Roes

Component: UncategorizedDocumentation
Type: UncategorizedCleanup/optimization

comment:2 Changed 14 months ago by Mariusz Felisiak

Resolution: wontfix
Status: newclosed

IMO ModelState.field_cache is an implementation detail and shouldn't be documented. There is an internal API FieldCacheMixin with field.is_cached(instance) (see #16043) for working with the model's fields value cache which I would use for your use case, but I don't think we should document it.

Note: See TracTickets for help on using tickets.
Back to Top