Michael Ward
Michael Ward

Reputation: 526

QuerySet filter ArrayField contains exact match

I have a model that generally looks like this:

class CategoryModel(models.Model):
    categories = ArrayField(..)

Let's say I have two categories, "categoryA" and "categoryB"

categoryA's categories is equal to [123, 562], and categoryB's categories is equal to [5, 32]

When I want to query for CategoryModels which contain exactly 5 as an item in it's categories list, I use CategoryModel.objects.filter(categories__icontain=5)

Unfortunately, the above query returns both categoryA and categoryB, not just categoryB. What is the proper way to perform this query?

Upvotes: 4

Views: 4644

Answers (1)

Nishant Nawarkhede
Nishant Nawarkhede

Reputation: 8400

You can use iexact,

CategoryModel.objects.filter(categories__1__iexact=5)

Here 1 extactly matches to first element.


from docs:

from django.db import models
from django.contrib.postgres.fields import ArrayField

class Post(models.Model):
    name = models.CharField(max_length=200)
    tags = ArrayField(models.CharField(max_length=200), blank=True)

    def __str__(self):
        return self.name

Index transforms

>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
>>> Post.objects.create(name='Second post', tags=['thoughts'])

>>> Post.objects.filter(tags__0='thoughts')
<QuerySet [<Post: First post>, <Post: Second post>]>

>>> Post.objects.filter(tags__1__iexact='Django')
<QuerySet [<Post: First post>]>

>>> Post.objects.filter(tags__276='javascript')
<QuerySet []>

Upvotes: 4

Related Questions