[Django]-Customizing functionality of field lookups for custom Django model fields

3👍

I can’t understand why you need to have such a custom field. As far as I can see, ‘year’ and ‘is_certain’ are perfectly suitable to store in 2 separated fields. By doing so, first, searching by year or year range is easier. Second, searching will be also be significantly more efficient, especially when there are a large amount of data. Last but not least, you don’t need to bother how to correctly implement a customized field anymore.

So I suggest you explain the fundamental reason why you need to store those two naturally disparate types of data into a single column in your database table. And maybe we can point out a simpler way to achieve your real goals.

3👍

Here’s something that I found useful:
Creating custom Field Lookups in Django

A more flexible way to do this is to write a custom QuerySet as well as a custom manager. Working from ozan’s code:

class PersonQuerySet(models.query.QuerySet):
    def in_age_range(self, min, max):
        return self.filter(age__gte=min, age__lt=max)

class PersonManager(models.Manager):
    def get_query_set(self):
         return PersonQuerySet(self.model)

    def __getattr__(self, name):
        return getattr(self.get_query_set(), name)

class Person(models.Model):
    age = #...
    objects = PersonManager()

This allows you to chain your custom query. So both these queries would be valid:

Person.objects.in_age_range(20,30)
Person.objects.exclude(somefield = some_value).in_age_range(20, 30)

0👍

Have you tried to change the behavior of get_prep_lookup to return just the year value when lookup_type == ‘year’? You could return int(value.split(‘/’)[0])

I’m not sure implementing such a custom field is the best option, is there a really good reason to avoid splitting the values into two separated fields?

Leave a comment