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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With