Skip to content

Code snippets

Atul Varma edited this page Oct 2, 2019 · 12 revisions

This page contains some code snippets that might be useful for one-off use. Since they're not part of the primary codebase, of course, they may not work anymore. Please feel free to delete or update them if that's the case.

Changing the names of RapidPro groups

I think our RapidPro syncing code added in #522 assumes that contact group names won't change. This means that if they do change, we need to manually rename them. Since we don't currently expose the RapidPro groups to the admin, we can do this via a script like this:

import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

RENAMES = {
    'HRP Tenants': 'Boop',
}

if __name__ == '__main__':
    import django

    django.setup()

    from rapidpro.models import ContactGroup
    from django.db import transaction

    with transaction.atomic():
        for (from_name, to_name) in RENAMES.items():
            cg = ContactGroup.objects.get(name=from_name)
            cg.name = to_name
            cg.save()
            print(f"Renaming '{from_name}' to '{cg.name}.")
        input("Press enter to proceed with renaming, or CTRL-C to abort.")

Caching derived data for onboarding

#401 contained a snippet we can run when we add a new derived data field for onboarding:

import os

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

    import django
    django.setup()

    from onboarding.models import OnboardingInfo

    for info in OnboardingInfo.objects.filter(pad_bbl=''):
        print(f"Updating address metadata for {info.user}.")
        info.save()

Listing users who reported as NYCHA but don't live in NYCHA housing

SELECT onb.user_id
FROM onboarding_onboardinginfo as onb
WHERE onb.lease_type = 'NYCHA' AND onb.pad_bbl <> '' AND onb.pad_bbl NOT IN (
    SELECT pad_bbl from nycha_nychaproperty
)

Conversely, here's a query for users who didn't self-report as NYCHA but are actually in a NYCHA BBL:

SELECT onb.user_id, onb.lease_type
FROM onboarding_onboardinginfo as onb
WHERE onb.lease_type <> 'NYCHA' AND onb.pad_bbl <> '' AND onb.pad_bbl IN (
    SELECT pad_bbl from nycha_nychaproperty
)

Listing users who have logged in since sending their letter of complaint

SELECT u.username, u.last_login, lr.created_at
FROM users_justfixuser AS u, loc_letterrequest AS lr
WHERE u.id = lr.user_id AND u.last_login > lr.created_at;
Clone this wiki locally