Filtering numbers from a django list
In my database I have a list of users, each one has an id, this id is CharField, it can contain either a string containing a number (e.g "058") or a string containing something like this "0Y5"
The id field, is not primary key
I want to filter the list of users to have only the ones that have an id that contain a valid number, like "005", "011", "122",
I tried this but it seems not working:
users = User.objects.filter(id.isnumeric == True)
You can use a regular expression (regex) in your query to find strings with numbers:
users = User.objects.filter(id__regex=r'^[0-9]*$')
The '^[0-9]*$' will match only numbers from the beginning (^) of the string to the end ($) where the numbers [0-9] can be repeated (*). The r means that what is between the quotes is to be interpreted as a raw string, so the \ will be not be considered an escape character.
I tried this and it works, I don't know if it is the best but it works!:
users = User.objects.all()
ids = [user.id for user in users if user.id.isnumeric()]