1

I have a jsonfield in Postgres db and data like below:

income_info = [
  {
    "id": "1",
    "name": "A",
    "min_income": 22000
  },
  {
    "id": "2",
    "name": "B",
    "min_income": 40000
  },
  {
    "id": "3",
    "name": "C",
    "min_income": 22000
  }
]

Now want to use gte and lte over the django orm queryset. Already tried

Employee.objects.filter(income_info__min_income__lte = 4000000)

but did not work at all.

models.py:

class Employee(models.Model):
    institute = models.ForeignKey(Institute, on_delete=models.DO_NOTHING)
    income_info = JSONField(default=list)
    others = models.TextField(null=True)
2
  • can you please share your models? Commented Jul 31, 2019 at 13:01
  • please check updated question Commented Jul 31, 2019 at 13:09

1 Answer 1

3

In django's documentation for querying JsonFields:

If the key is an integer, it will be interpreted as an index lookup in an array

As your json data is list of json datas, you need a query like this:

Employee.objects.filter(income_info__0__min_income__lte=4000000)
Sign up to request clarification or add additional context in comments.

3 Comments

Many Many Thanks
Is there a way to do that check only for the object with id 3? Considering I don't know its position in the array?
Im not sure if you can do that. Maybe you can add an identifier field in your json schema and have a separate filter for that in your query?

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.