1

I have this string variable

auxi_espec = '1, 3, 5, 7,'

And I need to convert it to array in order to make a queryset where I filter using __in. (Possibly I think I'll also need to slice the last comma).

1
  • Would you explain filter using __in, are you referring to something on django? Commented Mar 21, 2019 at 23:19

3 Answers 3

1

You need to use split() function:

>>> auxi_espec = '1, 3, 5, 7,'
>>> auxi_espec_lst = [x.strip() for x in auxi_espec.split(',')][:-1]
>>> auxi_espec_lst
['1', '3', '5', '7']

If you want to parse those numbers into integer:

>>> auxi_espec = '1, 3, 5, 7,'
>>> auxi_espec_lst = [int(x.strip()) for x in auxi_espec.split(',') if x]
>>> auxi_espec_lst
[1, 3, 5, 7]
Sign up to request clarification or add additional context in comments.

Comments

1

Django accepts a lot of iterables for in lookup, so if format of string you mentioned is set in stone this split is enough as list of strings will do.

ids = auxi_espec[0:-1].split(', ')  # ['1', '3', '5', '7']
instances = MyModel.objects.filter(id__in=ids)

Comments

0

Use regular expressions, they are awesome:

>>> import re
>>> auxi_espec = '1, 3, 5, 7,'
>>> indices = re.findall(r'(\d+)', auxi_espec)
>>> indices
['1', '3', '5', '7']
>>> [int(i) for i in indices]
[1, 3, 5, 7]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.