[Django]-Django get_or_create fails to set field when used with iexact

33👍

What you’re seeing is the correct behaviour.

get_or_create is shorthand for ‘get and return the object matching kwargs, if it doesn’t exist, create it using defaults‘. Your lookup is looking for an object where name is a case-insensitive match to 'cedar'. That object exists, so it is returned. Nothing more, nothing less.

Now if there was no match, Stéphane is right, and you would need to specify name in the defaults parameter. All lookups containing the lookup separator __ are stripped from the parameters passed to create().

👤knbk

31👍

According to the documentation, you can try to use default args (haven’t try this code):

p1, c1 = Provider.objects.get_or_create(
   defaults={'name':"Timber"}, 
   name__iexact="Timber"
)

It makes sense since you can then have the search and the object creation that differs.

Leave a comment