avlnx
avlnx

Reputation: 676

Django - Dynamic unique test for a model field

Is there a way to test for uniqueness of a field through a custom function?

Something like:

def custom_unique_test(instance):
    return global_test_results(instance)

class Category(models.Model)
    slug = models.SlugField(unique=custom_unique_test())

Thanks

Upvotes: 1

Views: 732

Answers (1)

AdamKG
AdamKG

Reputation: 14081

I'm assuming that your use case is that you only care about uniqueness within some relation with a larger group - eg, you don't need globally unique slugs, so unique=True is "too unique", you only need unique slugs for each Category within a CategoryGroup.

I'd suggest overriding Category.save(). You can check self.pk to see if this is an insert or update, and if it's insert, you can call your custom unique-check and slug-generation code before calling super(Category, self).save(*args, **kwargs).

Upvotes: 2

Related Questions