Reputation: 526
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 CategoryModel
s 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
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
>>> 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