我有一个django模型管理页面,想要使用它的搜索功能,所以我定义了一个像这样的search_fields:
search_fields = (
'name', 'email',
'vacancy__position__name',
'vacancy__location__name',
)
问题是'空缺'字段可以为空,但搜索找不到具有空'空缺'的项目,所以我深入研究它执行的sql并发现问题:
SELECT "testapp_subject"."name", "testapp_subject"."email",
FROM "testapp_candidate"
INNER JOIN "testapp_subject" ON ("testapp_candidate"."subject_ptr_id" = "testapp_subject"."id")
LEFT OUTER JOIN "testapp_vacancy" ON ("testapp_candidate"."vacancy_id" = "testapp_vacancy"."id")
LEFT OUTER JOIN "testapp_position" ON ("testapp_vacancy"."position_id" = "testapp_position"."id")
INNER JOIN "testapp_location" ON ("testapp_vacancy"."location_id" = "testapp_location"."group_ptr_id")
WHERE (UPPER("testapp_subject"."name"::text) LIKE UPPER(%j%)
OR UPPER("testapp_subject"."email"::text) LIKE UPPER(%j%)
OR UPPER("testapp_position"."name"::text) LIKE UPPER(%j%)
OR UPPER("testapp_location"."name"::text) LIKE UPPER(%j%) )
ORDER BY "testapp_candidate"."subject_ptr_id" DESC
如您所见,最后的INNER JOIN应该是LEFT OUTER JOIN。
我试图深入研究sql生成部分,看看发生了什么,但代码太复杂,无法阅读。任何人都知道发生了什么事,或者是否有人遇到过同样的情况?
以下是我案例的简化模型结构。
class Group(models.Model):
pass
class Organization(models.Model):
name = models.CharField(max_length = 50)
class Position(models.Model):
name = models.CharField(max_length=80)
class Location(Group):
name = models.CharField(max_length=80)
org = models.ForeignKey(Organization)
class Vacancy(models.Model):
position = models.ForeignKey(Position)
location = models.ForeignKey(Location)
date = models.DateField(default=datetime.now())
filled = models.BooleanField(default=False)
class Subject(models.Model):
org = models.ForeignKey(Organization, verbose_name="organization")
name = models.CharField(max_length = 50)
email = models.CharField(max_length = 85, null=True, blank=True)
class Candidate(Subject):
vacancy = models.ForeignKey(Vacancy, null=True, blank=True)