通过包含字符串过滤查询集

Filter queryset by containing a string

我需要过滤子字符串在给定文本中的所有 Alert 个对象。

class Alert(..):
    substring = CharField...

class Article(...):
    text = ...

我正在尝试 __in 但它似乎不起作用。

alerts = alerts.filter(Q(substring__isnull=True) | Q(substring='') | Q(substring__in=article.text))

你知道怎么做吗?我不能使用 contains 因为它是相反的。

可以使用.annotate(…) [Django-doc]注入articletext,然后过滤对象:

from django.db.models import F, Q, TextField, Value

Alert.objects.annotate(
    <b>article_text=Value(article.text, output_field=TextField())</b>
).filter(
    Q(substring=None) |
    Q(substring='') |
    <b>Q(article_text__contains=F('substring'))</b>
)