使用Right Join和WHERE IN子句

时间:2016-10-29 15:27:38

标签: python mysql sql django

考虑这些模型

class SearchableText(models.Model):
    searchable_text = models.TextField()

class SearchTerm(models.Model):
    searchabletext = models.ForeignKey(SearchableText, on_delete=models.CASCADE)
    term = models.CharField(max_length=100)

我想用django orm

编写这个sql语句的等价物
Select SearchableText.* right join SearchTerm on SearchTerm.searchabletext=SearchableText.id where SearchTerm.term in ("term 1","term 2","term 3")

我还想根据匹配条款的数量来订购结果,但我想这会产生另一个问题。

1 个答案:

答案 0 :(得分:0)

您可以使用Q功能。我想这可能是您正在寻找的查询:

from django.db.models import Q, F

SearchableText.objects.filter(Q(id=F('searchterm__searchabletext')), searchterm__term__in=['term1', 'term2', 'term3'])

生成的SQL查询如下:

SELECT app_searchabletext.* FROM app_searchabletext INNER JOIN app_searchterm ON (app_searchabletext.id = app_searchterm.searchabletext_id) WHERE (app_searchabletext.id = (app_searchterm.searchabletext_id) AND app_searchterm.term IN (term1, term2, term3))