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+)')
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.
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+)')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With