import os

from django.db.models import Q
from django.forms.models import model_to_dict

import django
import pandas as pd

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()

from ck.models import *

# patients = Patient.objects.filter(dead__isnull=True).order_by('timestamp')

L = []

for p in Patient.objects.order_by('id')[:10000]:
    print(p.id)

    t = p.treatment_set.order_by('date_started').first()
    if t is None:
        continue

    # report = p.electronicmedicalreport_set.filter(report_code='XrayTextReport').order_by('-check_date').first()
    r = p.electronicmedicalreport_set.filter(
        Q(report_class__icontains='MRI') |
        Q(report_class__icontains='M.R.I')
        ).order_by('-check_date').first()
    if r is None:
        continue

    tdate = t.date_started
    if tdate is None:
        tdate = t.date_completed
    if tdate is None:
        continue

    f = r.check_date-tdate
    print(f, p, t.date_started, r.check_date, r.report_class)

    d = {'followup': f}
    d.update(model_to_dict(p))
    d.update(model_to_dict(t))
    d.update(model_to_dict(r))

    L.append(d)

df=pd.DataFrame(L)

df.to_excel('ck_select.xlsx')

