Micah Pearce
Micah Pearce

Reputation: 1965

Django: unique id generator

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?

Upvotes: 2

Views: 170

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47374

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

Upvotes: 3

Related Questions