Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check containment in a django arrayfield?

Tags:

python

django

I am working with django models in Python where one of a model's fields is a ArrayField of id's, and, given a specific instance of a model with an ArrayField as a field, I want to check if a given id is in that instance's ArrayField. I have tried doing x in self.exampleArrayField but I get Value 'self.exampleArrayField' doesn't support membership test I have also tried x in list(self.exampleArrayField) but I have no idea if this even works (my editor, vscode, doesn't throw an error, but this is Python I'm working in). Is there a good way to do what I am trying to do?

like image 236
Conan G. Avatar asked Sep 06 '25 02:09

Conan G.


1 Answers

You want to use ORM methods to achieve this.

For an example, check out the documentation on ArrayFields

We have this model

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

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

To find posts that are tagged as "django"

>>> Post.objects.filter(tags__contains=['django'])
<QuerySet [<Post: First post>, <Post: Third post>]>

Here tags__contains expands to a special filter that actually queries within the array using PostgreSQL features.

Alternatively you can use the under-documented to_python method.

Which for your example would be:

x in self.exampleArrayField.to_python()

However, take a hard look at your code and consider if this is really necessary. If you are looping over a bunch of Python objects and calling this method, you are losing 100% of the performance benefits of Postgres operating on the arrays using the ORM.

like image 88
OregonTrail Avatar answered Sep 07 '25 19:09

OregonTrail