The way select_related works is it
creates a join on the foreign key columns so you return all the data together in one query. (Imagine it nested)
select_related only works on single value fields: foreign key and one to one.
Using select_related and prefetch related does not
change how you access the foreign fields.
To use prefetch_related on a reverse foreign key relationship, type
ModelName.objects.all().prefetch_related(‘model_name_set’)
The way prefetch_related works is it
does a separate lookup for each relationship, and does the ‘joining’ in python.
To log queries to the console, use
pip install django-queryinspect
MIDDLEWARE = [
‘qinspect.middleware.QueryInspectMiddleware’,
QUERY_INSPECT_ENABLED = True
LOGGING = {
'version': 1,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'qinspect': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': True,
},
},
}