Question

I have a model that holds a version number, which is stored, for historical reasons as a text field, like so x.y.z.

class Product(models.Model):
    version = TextField()

I'd like to perform requests on the database to say, fetch all products that have a major version number higher than 5. Or to get all products that have a minor version below 6.

I'm not too familiar with SQL abilities. Can I express such a thing with Django querysets ? Or perhaps with plain SQL if Django doesn't support it natively ?

Something like:

Product.objects.filter(version__some_expression_gt=5)

Is that possible ?


I know the obvious solution is to split the version field into its numerical counterparts but that's sadly not an option I have for stupid reasons.

Was it helpful?

Solution

https://docs.djangoproject.com/en/dev/ref/models/querysets/#regex

Product.objects.filter(version__regex=r'^[5-9]\.')

Just a "half" solution but i guess playing with regex is a good start.

OTHER TIPS

You can use Q for complex queries:

from django.db.models import Q

q_gt5 = Q( version__some_expression_gte="5" )
q_lt6 = Q( version__some_expression_lte="6" )

results_or    = Product.objects.filter(q_gt5 | q_lt6 )
results_and   = Product.objects.filter(q_gt5 & q_lt6 )
results_other = Product.objects.filter( ~q_gt5 & q_lt6 )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top