Задать вопрос

Тел: +7 965 3737 888





Unique Slugify

<p>Automatically create a unique slug for a model. </p>
<p>Note that you <em>don't</em> need to do obj.slug = ... since this method updates the instance's slug field directly. All you usually need is: unique_slugify(obj, obj.title)</p>
<p>A frequent usage pattern is to override the save method of a model and call unique_slugify before the super(...).save() call.</p>

Вопрос полезен? Да0/Нет0

Ответы (9):

Ответ полезен? Да0/Нет0

What's the point of adding .exclude(pk=instance.pk) to queryset. If instance.pk is not None, it means that it's an update operation and the field already has a slug. Shouldn't you just return in that case?

Ответ полезен? Да0/Нет0

Amazing snippet, it really helped me!

Ответ полезен? Да0/Нет0

eddified: Yep, for fringe cases like that, someone can just explicitly provide the queryset object.

Regarding when to use ._default_manager - you should use it when referencing potentially third-party model classes since you can't know if they have a manager named "objects".

Ответ полезен? Да0/Нет0

Good snippet. Maybe add a param that lets the user specify a custom exclude dict in cases where the model doesn't have a pk. But then again, a workaround would be to just specify a query set object that has what you want excluded, excluded. What's this about class.default_manager vs objects? When do I use one vs the other in my own code?

Ответ полезен? Да0/Нет0

Good point, seanos. Updated.

Ответ полезен? Да0/Нет0

Thanks for this.

One bug I found:

line 29 should be changed to:

if queryset is None:

otherwise if the argument queryset is empty, it will be re-populated with all rows from the model, leading to slug being modified when it should of been left alone.

Ответ полезен? Да0/Нет0


This is an interesting snippet. Does it still work with Django 1.0? Are there any thoughts in post-1.0 to update the slugfield and/or slugify functions to include this functionality?

I was also wondering, if I want to make a unique slug only for a given day would I enter something like this:

self.slug = unique_slugify(self,self.title,queryset=self.__class__._default_manager.filter(datetime_added=self.datetime_added))

Ответ полезен? Да0/Нет0

I just updated the snippet to also allow for changing the slug separator. I needed it to auto-generate a contrib.auth User username which was still editable in admin (doesn't allow the - character so I use slug_separator='_').

Ответ полезен? Да0/Нет0

Looks pretty similar - my way respects maximum length of the slug field, respects the _default_manager rather than assuming "objects".

Oh, and it also handles the case of changing a slug for an existing instance.

I probably should change mine to using a single query, but since it's only at save time for where I use this method, I didn't need it.