考虑这些模型
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")
我还想根据匹配条款的数量来订购结果,但我想这会产生另一个问题。
答案 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))