Django - how to write custom queryset per-field instead instead of per-model

334 Views Asked by At

I want to create a custom field such that if the field is queried, then the filter is always __iexact.

Example:

class Domain(models.Model):
    domain = models.IExactCharField()
    name = models.CharField()

I want a query like Domain.objects.filter('domain=newdomain') to be rewritten as Domain.objects.filter('domain__iexact=newdomain').

I understand you can do this with a custom manager, but I want adding the field to add the custom manager. And if a custom manager is already defined, I want the managers functionality to be chained. Is this possible? I was looking at the contribute_to_class method and thought it might have some potential when defining the field.

1

There are 1 best solutions below

4
On

The code below won't work - the lookup_type is being added elsewhere (in QuerySet) unfortunately. I'll take a look inside :)

class IExactCharField(models.CharField):
    def get_prep_lookup(self, lookup_type, value):
        return super(IExactCharField, self).get_prep_lookup('iexact', value)

It enforces iexact lookups - you can evantually add check of lookup_type before referencing to superclass.

PS. Bear in mind that some databases (SQLite) won't support case insensitive unicode string lookups.

EDIT: the only workaround I have is to make all domain fields lowercase on save() or some save signal.