简体   繁体   中英

Django Postgres ArrayField __contain lookup does not behave expectedly

This is my models.py :

class Dog(models.Model):
    name = models.CharField(max_length=200)
    data = JSONField()

    def __unicode__(self):
        return self.name

I did this in the django shell:

Dog.objects.create(name='Rufus', data={ 'breed': 'labrador', 'owner': { 'name': 'Bob', 'other_pets': [{  'name': 'Fishy',  }], }, })
Dog.objects.create(name='Meg', data={'breed': 'collie'})
Dog.objects.filter(data__breed__contains='l')

However when I did the last command it gave me an empy queryset return:

<QuerySet []>

The two objects (Meg and Rufus) should have both returned because they both contain l

This is my query:

SELECT "post_tagging_dog"."id", "post_tagging_dog"."name", "post_tagging_dog"."data" FROM "post_tagging_dog" WHERE "post_tagging_dog"."data" -> 'breed' @> '"l"'

try simply for + if :

for obj in Dog.objects:
    if 'l' in obj.data['breed']:
        return obj

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