Django 查询集排除正则表达式

Django queryset exclude regex

我有一个过滤请求的命令,我需要按照两条规则提取其中的一些请求。

应该

include '^https?:\/\/[^.]*\.?site\.co([^?]*[?]).*utm_.*$'
or
exclude '^https?:\/\/[^.]*\.?site\.([^\/]+\/)*'

因此,在计算一个可能的 SQL 表示时,我想到了:

exclude (
   matching '^https?:\/\/[^.]*\.?site\.([^\/]+\/)*'
   and
   not matching '^https?:\/\/[^.]*\.?site\.co([^?]*[?]).*utm_.*$'
)

在 django 中翻译成:

.exclude(
   Q(referer__iregex=r'^https?:\/\/[^.]*\.?site\.co([^?]*[?]).*utm_.*$') &
   Q(referer__not_iregex=r'^https?://[^.]*\.?site\.[^/]+/?[\?]*$'))

但不幸的是,__not_iregex 查找不存在。有什么解决方法?

您实际上可以使用 filter 作为您不想排除的部分:

queryset
    .filter(referer__iregex=r'^https?://[^.]*\.?site\.[^/]+/?[\?]*$')
    .exclude(referer__iregex=r'^https?:\/\/[^.]*\.?site\.([^\/]+\/)*')

所以这里你的 matching 进入 exclude 并且 not matching 进入 filter

或者,如果您真的想模仿 SQL 表示中的内容,您可以使用 ~Q

.exclude(
   Q(referer__iregex=r'^https?:\/\/[^.]*\.?site\.([^\/]+\/)*') &
   ~Q(referer__iregex=r'^https?://[^.]*\.?site\.[^/]+/?[\?]*$'))
   # notice use of ~ here