Daviddd
Daviddd

Reputation: 791

django queryset counts substrings in charField

One field in my model is a charField with the format substring1-substring2-substring3-substring4 and it can have this range of values:

"1-1-2-1"
"1-1-2-2"
"1-1-2-3"
"1-1-2-4"
"2-2-2-6"
"2-2-2-7"
"2-2-2-9"
"3-1-1-10"
"10-1-1-11"
"11-1-1-12"
"11-1-1-13"

For example I need to count the single number of occurrences for substring1. In this case there are 5 unique occurrences (1,2,3,10,11).

"1-X-X-X"
"2-X-X-X"
"3-X-X-X"
"10-X-X-X"
"11-X-X-XX"

Sincerely I don't know where I can start from. I read the doc https://docs.djangoproject.com/en/1.5/ref/models/querysets/ but I didn't find a specific clue.

Thanks in advance.

Upvotes: 0

Views: 715

Answers (3)

Samuele Mattiuzzo
Samuele Mattiuzzo

Reputation: 11048

results = MyModel.objects.all()

pos_id = 0

values_for_pos_id = [res.field_to_check.split('-')[pos_id] for res in results]
values_for_pos_id = set(values_for_pos_id)

How does this work:

  • first you fetch all your objects (results)
  • pos_id is your substring index (you have 4 substring, so it's in range 0 to 3)
  • you split each field_to_check (aka: where you store the substring combinations) on - (your separator) and fetch the correct substring for that object
  • you convert the list to a set (to have all the unique values)

Then a simple len(values_for_pos_id) will do the trick for you

NB: If you don't have pos_id or can't set it anywhere, you just need to loop like this:

for pos_id in range(4):
    values_for_pos_id = set([res.field_to_check.split('-')[pos_id] for res in results])
    # process your set results now
    print len(values_for_pos_id)

Upvotes: 1

Rob L
Rob L

Reputation: 3734

You could loop through these items (I guess they're strings), and add the value of each substring_n to a Set_n.

Since set values are unique, you would have a set, called Set_1, for example, that contains 1,2,3,10,11.

Make sense?

Upvotes: 0

Joseph Paetz
Joseph Paetz

Reputation: 876

Try something like this...

# Assumes your model name is NumberStrings and attribute numbers stores the string.
search_string = "1-1-2-1"
matched_number_strings = NumberStrings.objects.filter(numbers__contains=search_string)
num_of_occurrences = len(matches_found)
matched_ids = [match.id for match in matched_number_strings]

Upvotes: 0

Related Questions