What you wrote is roughly the way to do it, but you shouldn't call get()
on it all the time. Each time you do it you are making a separate db query.
Django fetches lazily from the database, when you indicate that you want the results. E.g.
# first enable some logging to see the database queries
import logging.config
logging.config.dictConfig({
'version': 1,
'formatters': {
'simple': {'format': '%(levelname)s %(message)s'},
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple',
},
},
'root': {
'level': 'WARNING',
'handlers': ['console'],
},
'loggers': {
'django.db.backends': {'level': 'DEBUG',},
},
})
# No query made
codes = RecordType.objects.filter(
industry_code__in=[cat.value for cat in enums.Category]
)
# show the query that will be made (roughly)
print(str(codes.query))
# force the queryset to be executed and return all the results.
# the queryset is executed when you iterate over it.
codes_by_industry_code = {
code.industry_code: code
for code in codes
}
# now you can set up your list:
permanent = [
(
codes_by_industry_code[category.value].internal_code,
self.labels.get(category, category.name)
)
for category in enums.Category
]
Now, if you want to be sure that the queries only happen in the right place, you should use a testing tool such as described in this question to test your code. That is the only way to be sure going forward that your code is doing what it should be in terms of db queries.