prefetch.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. from django.contrib.contenttypes.fields import GenericRelation
  2. from django.db.models import ManyToManyField
  3. from django.db.models.fields.related import ForeignObjectRel
  4. from taggit.managers import TaggableManager
  5. __all__ = (
  6. 'get_prefetchable_fields',
  7. )
  8. def get_prefetchable_fields(model):
  9. """
  10. Return a list containing the names of all fields on the given model which support prefetching.
  11. """
  12. field_names = []
  13. for field in model._meta.get_fields():
  14. # Forward relations (e.g. ManyToManyFields)
  15. if isinstance(field, ManyToManyField):
  16. field_names.append(field.name)
  17. # Reverse relations (e.g. reverse ForeignKeys, reverse M2M)
  18. elif isinstance(field, ForeignObjectRel):
  19. field_names.append(field.get_accessor_name())
  20. # Generic relations
  21. elif isinstance(field, GenericRelation):
  22. field_names.append(field.name)
  23. # Tags
  24. elif isinstance(field, TaggableManager):
  25. field_names.append(field.name)
  26. return field_names