2

I have a Model with a JSON Field.

data = JSONField(default=dict)

Is there an efficient way - or queryset filter - to find all instances of this Model that do not have a speicfic key in the json field.

Django documentation includes has_key function for JSON field.

Essentially i'm looking for a way to do not_has_key

My current method:

queryset = MyObj.objects.all()
for obj in queryset:
    if 'my_key' not in obj.data:
        do_work()
    else:
        pass
        #key_already_exists

Many thanks

Dan Walters
  • 1,218
  • 1
  • 18
  • 30
  • I believe that's the most pythonic way to check if a key in (or in your case, is not) in a dictionary. – Higor Rossato Nov 01 '19 at 09:37
  • another way is using the ~Q operator [Q operator](https://stackoverflow.com/a/1154977/11225821) – Linh Nguyen Nov 01 '19 at 09:41
  • 1
    If you don't want to iterate through them all and just get a collection of instances that *do not have the key* then use `exclude` with `has_key`: e.g. `SomeModel.objects.exclude(jsonfield__has_key='field_name')` – NeilG Jul 10 '22 at 16:56

0 Answers0