0

I would like to get an instance of one of my Django models by using dictionary in an insensitive case way. For the moment I'm using:

my_model.objects.get(**dictionary)

But I don't get the instance if there is a difference of lower / upper case between what there is in my dictionary and the fields of the instance.

Do you think there is a clean way to perform this operation ?

Antoine
  • 577
  • 4
  • 17
  • 1
    No, in fact Django does not know *how* you call it. If you call `some_function(**some_dict)`, Python will simply replace that with `some_function(key1=val1, key2=val2)`, etc. This is just argument unpacking. – Willem Van Onsem Feb 01 '19 at 19:14
  • Thanks to you and this solution: https://stackoverflow.com/questions/11743207/django-model-case-insensitive-query-filtering, I found how to do it.I just have to rename the keys of my dictionary from 'key' to 'key__iexact' and it's working ! – Antoine Feb 01 '19 at 19:22

1 Answers1

4

Django takes the WHERE filter to load the object entirely from the keys of the dictionary you provide. It is up to you to provide field lookups; you can use the iexact field lookup type, but you do need to use this on textual fields.

So if you wanted to match a specific string field, case insensitively, add __iexact to the key in dictionary; e.g. {'foo': 'bar'} becomes {'foo__iexact': 'bar'}.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343