Created
December 9, 2019 16:22
-
-
Save phpdude/50675114aaed953b820e5559f8d22166 to your computer and use it in GitHub Desktop.
How do I make and access regex capture groups in Django without RawSQL? (https://stackoverflow.com/questions/59198776/how-do-i-make-and-access-regex-capture-groups-in-django-without-rawsql/59252836#59252836)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib.admin import ModelAdmin, register | |
from django.db.models import IntegerField | |
from django.db.models.functions import Cast | |
from django.db.models.expressions import Func, Value | |
from .models import Foo | |
class RegexpMatches(Func): | |
function = 'REGEXP_MATCHES' | |
def __init__(self, source, regexp, flags=None, group=None, output_field=None, **extra): | |
template = '%(function)s(%(expressions)s)' | |
if group: | |
if not hasattr(regexp, 'resolve_expression'): | |
regexp = Value(regexp) | |
template = '({})[{}]'.format(template, str(group)) | |
expressions = (source, regexp) | |
if flags: | |
if not hasattr(flags, 'resolve_expression'): | |
flags = Value(flags) | |
expressions += (flags,) | |
self.template = template | |
super().__init__(*expressions, output_field=output_field, **extra) | |
@register(Foo) | |
class Foo(ModelAdmin): | |
list_display = ['id', 'required_field', 'required_field_string'] | |
def get_queryset(self, request): | |
qs = super().get_queryset(request) | |
return qs.annotate( | |
required_field=Cast(RegexpMatches('id', r'^(.*\D)([0-9]*)$', group=2), output_field=IntegerField()), | |
required_field_string=RegexpMatches('id', r'^(.*\D)([0-9]*)$', group=2) | |
) | |
def required_field(self, obj): | |
return obj.required_field | |
def required_field_string(self, obj): | |
return obj.required_field_string |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
class Foo(models.Model): | |
id = models.CharField(primary_key=True, max_length=100) | |
def __str__(self): | |
return self.id |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment