我正在将Django与Postgres 10数据库引擎一起使用,以通过表单构建基于Web的搜索工具。在Django中通过原始SQL执行查询时,在pgAdmin的Ouery Tool中运行相同的SQL时,我仅收到3条记录,而与902相反。
我尝试使用django ORM来构建查询,但是示例如此简单,以至于我无法成功地将其用于我的需求。以下列方式查询多个模型的指南将不胜感激。
Django Raw SQL语句
ProstateUpper = 'Prostate'
ProstateLower = 'prostate'
GenderMale = 'Male'
GenderAll = 'All'
Master_Query = Eligibilities.objects.raw('''SELECT DISTINCT ON (Eligibilities.nct_id) Eligibilities.id, Studies.brief_title, Eligibilities.nct_id, Conditions.name, Eligibilities.gender, Eligibilities.minimum_age, Eligibilities.maximum_age, Eligibilities.criteria, Interventions.intervention_type, Interventions.name, Facilities.city, Facilities.state, Facilities.country, Brief_Summaries.description, Facility_Contacts.name, Facility_Contacts.email FROM Eligibilities INNER JOIN Studies on Studies.nct_id = Eligibilities.nct_id INNER JOIN Conditions on Conditions.nct_id = Eligibilities.nct_id INNER JOIN Interventions on Interventions.nct_id = Eligibilities.nct_id INNER JOIN Facilities on Facilities.nct_id = Eligibilities.nct_id INNER JOIN Brief_Summaries on Brief_Summaries.nct_id = Eligibilities.nct_id INNER JOIN Facility_Contacts on Facility_Contacts.nct_id = Eligibilities.nct_id WHERE ((Conditions.name LIKE %s OR Conditions.name LIKE %s)) AND (gender LIKE %s OR gender LIKE %s) ''', [ProstateUpper, ProstateLower, GenderMale, GenderAll])[:1000]
pgAdmin SQL语句
SELECT DISTINCT ON (eligibilities.nct_id) eligibilities.id, studies.brief_title, eligibilities.nct_id, conditions.name, eligibilities.gender, eligibilities.minimum_age, eligibilities.maximum_age, eligibilities.criteria, interventions.intervention_type, interventions.name, facilities.city, facilities.state, facilities.country, brief_summaries.description, facility_contacts.name, facility_contacts.email
FROM ctgov.eligibilities
INNER JOIN ctgov.studies on studies.nct_id = eligibilities.nct_id
INNER JOIN ctgov.conditions on conditions.nct_id = eligibilities.nct_id
INNER JOIN ctgov.interventions on interventions.nct_id = eligibilities.nct_id
INNER JOIN ctgov.facilities on facilities.nct_id = eligibilities.nct_id
INNER JOIN ctgov.brief_summaries on brief_summaries.nct_id = eligibilities.nct_id
INNER JOIN ctgov.facility_contacts on facility_contacts.nct_id = eligibilities.nct_id
WHERE ((conditions.name LIKE '%Prostate%' OR conditions.name LIKE '%prostate%')) AND (gender LIKE '%Male%' OR gender LIKE '%All%')
;
我希望输出的记录数量和内容相同,因为它们正在查询相同的源。
答案 0 :(得分:0)
塞尔柱克的评论使我得出了正确的结果。馈送Where子句的变量需要更改以反映查询中的Conditions.name LIKE '%prostate%'
,因此:
ProstateUpper = '%Prostate%'
ProstateLower = '%prostate%'
GenderMale = '%Male%'
GenderAll = '%All%'