[英]How to make this django model query
My model looks something like this: 我的模型看起来像这样:
uri
-----
1@domainXY
2@domainYZ
3@domainZK
I want to match username parts of this uris to some list. 我想将此uris的用户名部分与某些列表相匹配。 So if there is no @domain part of the uri, I would type:
所以如果uri没有@domain部分,我会输入:
L = ['1', '2']
model.objects.filter(uri__in=L)
but how can I ignore the domain part in this query? 但是如何忽略此查询中的域部分? So what I need is something like this (I understand this is not django-way how to do it, but just to explain what I'm trying to do):
所以我需要的是这样的东西(我知道这不是django-way如何做到这一点,而只是为了解释我正在尝试做什么):
L = ['1', '2']
model.objects.filter(strip_domain_part_with_at(uri)__in=L)
I cannot and do not want to make any raw queries. 我不能也不想做任何原始查询。
Depending on your data you may be able to use __startswith
: 根据您的数据,您可以使用
__startswith
:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#startswith https://docs.djangoproject.com/en/dev/ref/models/querysets/#startswith
However if your numeric prefixes go beyond single digits (and are not zero-padded to constant length) a simple string comparison like that isn't going to work properly. 但是,如果您的数字前缀超出单个数字(并且不是零填充到常量长度),那么这样的简单字符串比较将无法正常工作。 (ie
1
, 10
, 104
all 'start with' 1
) (即
1
, 10
, 104
都'开始' 1
)
You can try a __regex
query instead: 您可以尝试使用
__regex
查询:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#regex https://docs.djangoproject.com/en/dev/ref/models/querysets/#regex
eg 例如
model.objects.filter(uri__regex==r'^(%s)@.+' % '|'.join(L))
You should profile the performance of this query on your data as use of regex may be slow (even database backends which support __regex
natively probably can't use indexes for a regex query, so will do a full table scan). 您应该对数据的性能进行分析,因为正则表达式的使用可能很慢(即使支持
__regex
本身的数据库后端可能无法使用索引进行正则表达式查询,因此将执行全表扫描)。
Probably a better approach would be to store the part before the @
in an additional model field so you can run a simpler query on it. 可能更好的方法是将部件存储在
@
之前的附加模型字段中,以便您可以对其运行更简单的查询。
from django... import Q
qry = " | ".join(["Q(uri__startswith ='%s@')"%v for v in L])
model.objects.filter(eval(qry))
there may be a better way to do it than with eval 可能有比使用eval更好的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.