Search code examples
pythondjangodjango-queryset

django filter on the basis of text length


I would like to filter my model on the basis of the length of the text Something like

MyModel.objects.filter(len(text) > 10)

where text is a Char or Text field in MyModel model


Solution

  • It would be much better and faster if you just add a column that pre-calculates(memoizes) the length of the text.

    e.g.

    class MyModel(models.Model):
        text = models.TextField()
        text_len = models.PositiveIntegerField()
    
         def save(self, *args, **kwargs):
             self.text_len = len(self.text)
             return super(MyModel, self).save(*args, **kwargs)
    
    MyModel.objects.filter(text_len__gt = 10)     # Here text_len is pre-calculated by us on `save`