2

I have a pres_save feature that creates a unique ID for a field in a model. I am having trouble checking to see if the field is unique:

def pre_save_create_invoice_id(sender, instance, *args, **kwargs):
    if not instance.invoice_id:
        instance.invoice_id = unique_id_generator('invoice_id',instance)

pre_save.connect(pre_save_create_invoice_id, sender=Invoice)

def unique_id_generator(field,instance):
    new_id = random_string_generator()
    Klass = instance.__class__
    qs_exists = Klass.objects.filter(field=new_id).exists()
    if qs_exists:
        return unique_slug_generator(instance)
    return new_id

When I run the code, I get the error that 'Cannot resolve keyword 'field' into field. Choices are: ... invoice_id...'

Basically it errors out on this line: qs_exists = Klass.objects.filter(field=new_id).exists() saying that 'field' is not a field in the model.

Why is it using the word 'field' instead of the value for field e.g. invoice_id?

1 Answer 1

3

Since you are passing as field name string you cannot use filter(field=value) syntax. It's same as filter('invoice_id'=value) which is not valid syntax. Use unpacked dict instead:

qs_exists = Klass.objects.filter(**{field: new_id}).exists()
if qs_exists:
    return unique_slug_generator(instance)
return new_id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.