Forced numeric comparison on CharField in djangos orm filter

I have a dynamic data structure in my django model, basically this is one CharField where text and numbers can be stored:

class CSFeature(models.Model):
    csfFeatureValue = models.CharField(max_length=200)

      

my Filter:

cslist = CSFeature.objects.filter(csfFeatureValue__gte=filter_value)

      

The problem is that string comparison takes place, for example

stored value (csfFeatureValue) = 23

  • Filter
  • filter_value = 13 returns the model
  • filter_value = 3 filter does not return model (string comparison)

How can I force a numeric comparison here? Since this is a generic datamodel, I cannot change the datatype of the model ...

+3


source to share


1 answer


This seems like bad design templates. We assume that the discriminator rule: "csfFeatureValue" is numeric.

You can override the save method for the correct field to save:

'13'

      

We will store:

'  _total of 198 blank spaces_ 13'  

      



Here he is:

class CSFeature(models.Model):
    csfFeatureValue = models.CharField(max_length=200)

    def save(self, *args, **kwargs):
        if self.csfFeatureValue.isdigit():
            self.csfFeatureValue = "{0:200}".format(int( self.csfFeatureValue ))
        super(Model, self).save(*args, **kwargs)  

      

now you can compare:

filter_value = "{0:200}".format( 3 )
cslist = CSFeature.objects.filter(csfFeatureValue__gte=filter_value)  

      

I repeat: double-check the design . This answer is just a technical approach to solving the related problem, but your problem is not with the django query api operation, but with the model design .

0


source







All Articles