Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex in Django query set

I'm trying to write a Django query that will filter by a particular regex pattern.

I want to filter by a code that pulls out any cases where there's any non-digit character followed by a number, followed by a non-digit character (a white space is fine).

Just say some codes are AJDP8EP, jsif28EP, EROE88, oskdpoeks8.

So I want my results to return: AJDP8EP, oskdpoeks8.

This is my query, but it's not recognizing things properly. Number is a variable.

results = Book.objects.filter(author__contains = firstname,type = "Fiction").filter(code__regex = r'^(\D+)(number)(\D+)')
like image 357
user1328021 Avatar asked Oct 21 '25 21:10

user1328021


2 Answers

You cannot use a variable inside your quoted regex expression. Try concatenating strings like:

r"^(\D+)(" + str(number) + ")(\D+)"

This converts your number variable to a string in case it is not already.

Also, as indicated in one of the comments to your question, oskdpoeks8 will not match your pattern. If you want to catch cases where number may come at the end of the code, one solution would be:

r"^(\D+)(" + str(number) + ")(\D*)"

Note the replacement of the + with an * to catch that case of zero occurrences.

like image 192
Fiver Avatar answered Oct 23 '25 11:10

Fiver


With python 3+ and newer versions on django you can make use of f-strings to pass variables to regex and use them in queries. For example:

Car.objects.filter(
    car_code__regex=rf'^{settings.SOME_SETTING}0*(\d+)$'
)

For the OP's case:

results = Book.objects.filter(author__contains = firstname,type = "Fiction").filter(code__regex = rf'^(\D+){number}(\D+)')
like image 32
Eric O. Avatar answered Oct 23 '25 09:10

Eric O.