How to create a unique_for_field pool in Django?

Django has a unique_for_date property that you can set when adding a SlugField to your model. This causes slug to be unique only for the date of the field you specify:

class Example(models.Model): title = models.CharField() slug = models.SlugField(unique_for_date='publish') publish = models.DateTimeField() 

What would be the best way to achieve the same functionality for a non-DateTime field like ForeignKey? Ideally, I want to do something like this:

 class Example(models.Model): title = models.CharField() slug = models.SlugField(unique_for='category') category = models.ForeignKey(Category) 

Thus, I could create the following URLs:

 /example/category-one/slug /example/category-two/slug /example/category-two/slug <--Rejected as duplicate 

My ideas so far:

  • Add a unique index for slug and categoryid to the table. This requires code outside of Django. And will the built-in administrator be able to handle this correctly if the insert / update does not work?

  • Cancel the save for the model and add my own check, throwing an error if duplicate exists. I know this will work, but it does not look very dry.

  • Create a new slug field that inherits from the base and add unique_for functions there. . This seems like the best way, but I looked at the unique_for_date main code, and it didn't look very intuitive to extend it.

Any ideas, suggestions or opinions on the best way to do this?

+6
django django-models slug
source share
1 answer

What about unique_together ?

 class Example(models.Model): title = models.CharField() slug = models.SlugField(db_index=False) category = models.ForeignKey(Category) class Meta: unique_together = (('slug','category'),) # or also working since Django 1.0: # unique_together = ('slug','category',) 

This creates an index, but it is not outside of Django;) Or did I skip the point?

+14
source share

All Articles