2

I have a JSONField in Django model like this:

#Object1 JSONField:
{"Fruits": ["banana", "cherry", "apple", "strawberry"], "Vegetables": ["broccoli",  "cucumber", "eggplant"]}
#Object2 JSONField:
{"Fruits": ["fig", "coconut", "pear"], "Vegetables": ["broccoli",  "cucumber", "eggplant"]}

When I only search one item in objects it return the result correctly:

def get_queryset(self, *args, **kwargs):
    qs = super(FruitsListView, self).get_queryset(*args, **kwargs)
    qs = qs.filter(data__Fruit__icontains='cherry')
    # This return Object1 currectly

but the problem is where I want to get those objects that their Fruits value have at least one of the items of the list:

def get_queryset(self, *args, **kwargs):
    qs = super(FruitsListView, self).get_queryset(*args, **kwargs)
    lst = ['cherry', 'coconut']
    qs = qs.filter(data__Fruit__icontains=lst)

I expect this to return both object1 and object2, but it does not return anything.

1 Answers1

0

This should help you sort this out:

def get_queryset(self, *args, **kwargs):
    qs = super(FruitsListView, self).get_queryset(*args, **kwargs)
    qs = qs.filter(Q(data__Fruit__icontains='cherry') | Q(data__Fruit__icontains='coconut'))
    (...)

Keep in mind this kind of condition generates sql code that can slow down rapidly on large table. Analyse your requirements carefully.

  • 1
    This is a good solution, but it may not be appropriate to use this method when the list has many items. –  Jul 03 '21 at 20:31