cirik
cirik

Reputation: 179

How to filter with "contains"?

I try to filter and get some set of objects using this segment.

baseSet = ThreadedComment.objects.filter(tree_path__contains = baseT.comment_ptr_id)

but it brings some objects that are not supposed to be there. For example, my baseT.comment_ptr_id is 1, it brought items with these tree_path.

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

The last 2 ones are not supposed to be here. But since their tree_path contains "1" filter brings those as well.

How can I write regex to create a filter that does not bring those items?

Upvotes: 3

Views: 205

Answers (2)

Paul Eastlund
Paul Eastlund

Reputation: 6933

Why not do

baseSet = ThreadedComment.objects.filter(tree_path__contains = ('%010i' % int(baseT.comment_ptr_id)))

so that the search string for id=1 will be "0000000001" and won't be a substring of "0000000011"?

EDIT: As per the comment below, it might be better to use COMMENT_PATH_DIGITS. This is a little messier because you're using formatting to set a formatting tag. It looks like this:

tree_path__contains = ('%%0%ii' % COMMENT_PATH_DIGITS % int(baseT.comment_ptr_id))

Upvotes: 3

Samus_
Samus_

Reputation: 2993

the regexp would be '(^|/)0*%d(/|$)' % baseT.comment_ptr_id and you use it with tree_path__regex

read about MPTT for alternatives to this approach.

Upvotes: 2

Related Questions