简体   繁体   中英

JSONField contains in Django

Hi im trying to know if a list contains another list, for this im using django + djongo, but i dont if i'm doing the query correctly

My model is


class Item(models.Model):
    name = models.CharField(max_length= 255)
    _id = models.ObjectIdField(primary_key = True)
    sku = models.JSONField(null= True)
    providers= models.JSONField(null= True)
    generic = models.JSONField(null= True)
    is_validated = models.BooleanField(default = False)
    tags = models.JSONField(null= True)
    objects = models.DjongoManager()

My serializer

class ItemSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Item
        fields = (
            '__all__'
        )

generic is a list of strings like: ["martillo", "s2","s3","s4"]

I want to get all items which the generic list contains the given list, i'm trying the next query but it returns all the items in database

items = models.Item.objects.filter(generic__contains = ['martillo'])

What i'm doing wrong?

import operator
from django.db.models import Q

Item.objects.filter(reduce(operator.and_, (Q(generic__contains=x) for x in ["martillo", "s2","s3","s4"] )))

Which is the equivalent of

Item.objects.filter(Q(generic__contains='martillo') & Q(generic__contains='s2') & Q(generic__contains='s3') etc...)

From https://stackoverflow.com/a/4824810/1730167

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM