我有一个返回两行的 sql 选择查询:
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 中时,查询集似乎不是可迭代的。
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 查询(我以为我上周检查并重新检查了它们)。向任何为此花费时间的人道歉。