2

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):
    param = models.ForeignKey(Param)
    value = models.IntegerField()
    created = models.DateTimeField(default=datetime.now, blank=True)

I wanted to create dynamic constructor. Is there any library or method for create dynamic logic filter like as Apache Lucene or Solr? I mean something like this:

dyn_filter = parse("(value < 200 AND value__s_name == 'pressure') 
    OR (value > 10 AND value__s_name == 'depth')")
result = ParamValue.objects.filter(dyn_filer)
4
  • do you want parse sql or just generate filter dynamic? Commented Sep 20, 2017 at 22:07
  • I want generate filter, maybe. Now I'm look at whoosh (whoosh.readthedocs.io/en/latest/querylang.html) Commented Sep 20, 2017 at 23:30
  • Do you also want a parser or do you only want the ORM to execute the equivalent query? Commented Sep 20, 2017 at 23:42
  • 1
    I think that I need parser, because query string ("(value < 200 AND ....)") should be stored in database Commented Sep 20, 2017 at 23:50

2 Answers 2

3

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')
)
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

It's PERFECT! Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.