我尝试使用此段过滤并获取一些对象集。
baseSet = ThreadedComment.objects.filter(tree_path__contains = baseT.comment_ptr_id)
但它带来了一些不应该存在的对象。 比如我的baseT.comment_ptr_id是1,它带来了带有这些tree_path的items。
comment_ptr_id=1 treepath = 0000000001
comment_ptr_id=3 treepath = 0000000001/0000000003
comment_ptr_id=4 treepath = 0000000001/0000000003/0000000004
comment_ptr_id=8 treepath = 0000000001/0000000003/0000000004/0000000008
comment_ptr_id=10 treepath = 0000000006/0000000010
comment_ptr_id=11 treepath = 0000000011
最后两个不应该在这里。但由于他们的 tree_path 包含“1” 过滤器也带来了这些。
我如何编写正则表达式来创建不带这些项目的过滤器?
最佳答案
为什么不做
baseSet = ThreadedComment.objects.filter(tree_path__contains = ('%010i' % int(baseT.comment_ptr_id)))
这样 id=1 的搜索字符串将是“0000000001”,而不是“0000000011”的子字符串?
编辑:根据下面的评论,最好使用 COMMENT_PATH_DIGITS。这有点困惑,因为您正在使用格式化来设置格式化标签。它看起来像这样:
tree_path__contains = ('%%0%ii' % COMMENT_PATH_DIGITS % int(baseT.comment_ptr_id))
关于python - 如何使用 "contains"进行过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8789716/