Skip to content Skip to sidebar Skip to footer

Dynamic Logic Query Builder In Django

I'm have 2 table in DB: class Param(models.Model): s_name = models.CharField(max_length=200) n_name = models.CharField(max_length=200) class ParamValue(models.Model):

Solution 1:

Django ORM has the Q objects which allows you to write the logic operation OR with the Queryset parameters.

The bellow example does exactly what your text ("(value < 200 AND value__s_name == 'pressure') OR (value > 10 AND value__s_name == 'depth')") asks for:

from django.db.models import Q
ParamValue.objects.filter(
    Q(value__lt=200, param__s_name='pressure') | Q(value__gt=10, param__s_name='depth')
)

Solution 2:

Check the library DjangoQL. It supports logical operators, comparison operators, parenthesis, table joins, etc.

from django.db import models

from djangoql.queryset import DjangoQLQuerySet


class Book(models.Model):
    name = models.CharField(max_length=255)
    author = models.ForeignKey('auth.User')

    objects = DjangoQLQuerySet.as_manager()

With the example above you can perform search like this:

qs = Book.objects.djangoql(
    'name ~ "war" and author.last_name = "Tolstoy"'
)

And DjangoQL will execute the equivalent Django queryset.


Post a Comment for "Dynamic Logic Query Builder In Django"