Home > database >  Filtering ArrayField by entire and exact array only?
Filtering ArrayField by entire and exact array only?

Time:03-05

I have a slug ArrayField on a model.

How can I filter or get by the entire exact array only?

I'm currently doing something like this:

search = f'["a", "b", "c"]'

list = search[2:-2].split("', '")
dict = {}
for n, item in enumerate(list):
  dict[f"slug__{n}"] = item

obj = queryset.filter(**dict)

However, this returns any object where the slug begins with "a", "b", and "c". E.g.

["a", "b", "c"]
["a", "b", "c", "d"]
["a", "b", "c", "d", "e"]
["a", "b", "c", "123"]

How do I do a filter or get so that only the entire and exact slug match returns? I.e. obj only returns objects with a slug of ["a", "b", "c"]

CodePudding user response:

To filter an ArrayField by an exact match you can just pass the list to match against to a filter

queryset = queryset.filter(slug=["a", "b", "c"])
  • Related