Bobort
Bobort

Reputation: 3218

How do we convert field values to a numeric type in the Django ORM?

I have a CharField on my model, and I want to retrieve only the numbers in that CharField.

For example:

DEMO
025-SP
026
028

I want to retrieve these elements:

025-SP
026
028

And ultimately get the maximum value of the numbers in the strings:

>  Max(025, 026, 028) = 028

The padding zeroes are not necessary if that helps.

Upvotes: 0

Views: 91

Answers (1)

NS0
NS0

Reputation: 6096

You can filter using a regular expression. For example:

Model.objects.filter(value__regex=r'^\d+')

Upvotes: 2

Related Questions