The above logic was pulled out and made more general (so it could be used outside of an API request). It's now in main/models.py, below.