Django原始sql生成一个我不能迭代的查询集 - 停止

时间:2012-04-16 08:52:42

标签: sql django django-queryset

我有一个sql select查询,它返回两行:

SELECT contacts_patientcontact.contact_id, patient_firstname, recent_mailouts
FROM contacts_patientcontact
INNER JOIN patients_patientcore
ON contacts_patientcontact.patient_id = patients_patientcore.patient_id
LEFT JOIN   (SELECT contact_id, COUNT(*) as recent_mailouts
    FROM contacts_communicationinstance
    WHERE communication_type = 'questionnaire mailout'
    GROUP BY contact_id) mail_outs
ON contacts_patientcontact.contact_id = mail_outs.contact_id
WHERE contact_date BETWEEN '2012/03/05' AND '2012/03/12'
AND contact_type = 'Postal Questionnaire'
AND patient_dead != 1
AND consent_withdrawn IS NULL
AND lost_follow_up != 1
AND (key = 'A' OR key = 'C')
AND     (recent_mailouts < 1 
OR recent_mailouts IS NULL);

但是当我使用raw方法将它添加到django中时,queryset似乎不可迭代。

def weekly_questionnaire_mailout_query(monday):
    """
    Returns a query set of PatientContact objects for patients
    due a mailout in the week following the parameter 'monday'.
    """
    nxt_monday = monday + datetime.timedelta(weeks=1)
    nxt_monday_str = nxt_monday.strftime('%Y/%m/%d')
    monday_str = monday.strftime('%Y/%m/%d')
    contacts = PatientContact.objects.raw("""
        SELECT contacts_patientcontact.contact_id
        FROM contacts_patientcontact
        INNER JOIN patients_patientcore
        ON contacts_patientcontact.patient_id = patients_patientcore.patient_id
        LEFT JOIN    (SELECT contact_id, COUNT(*) as recent_mailouts
                FROM contacts_communicationinstance
                WHERE communication_type = 'questionnaire mailout'
                GROUP BY contact_id) mail_outs
        ON contacts_patientcontact.contact_id = mail_outs.contact_id
        WHERE contact_date BETWEEN '%s' AND '%s'
        AND contact_type = 'Postal Questionnaire'
        AND patient_dead != 1
        AND consent_withdrawn IS NULL
        AND lost_follow_up != 1
        AND (cora = 'A' OR cora = 'C')
        AND     (recent_mailouts < 1 
            OR recent_mailouts IS NULL);   
        """  % (monday_str, nxt_monday_str)
    )
    return contacts

contacts = weekly_questionnaire_mailout_query(monday)
for contact in contacts:
    patients.add(contact.patient_id)

永远不会达到最后一行。 (我已经检查了日期是否正确,我在下面列出了PatientContact模型。)

class PatientContact(models.Model):
    contact_id = models.AutoField(primary_key=True)
    patient_id = models.ForeignKey(PatientCore, db_column="patient_id",
                               verbose_name="patient")
    # additional fields..

我对此感到茫然 - 而不是在查询集中显示项目,而我的(pydevd)调试器显示了一个RawQuerySet对象。相同的函数(使用相同的参数)返回一个djangotables2处理正常的对象(生成我希望从sql输出中获得的表)。

修改

那令人尴尬 - 毕竟是日期 - 我实际上并没有运行相同的SQL查询(我以为我上周检查并重新检查了它们)。对任何花时间在这上面的人道歉。

1 个答案:

答案 0 :(得分:0)

这是一个错误。我正在运行错误的代码。

解决方案是要更加小心!