justinmayer / django-autoslug

AutoSlugField for Django. Supports (but not does not require) unidecode/pytils for transliteration. Old issue tracker is at Bitbucket: https://bitbucket.org/neithere/django-autoslug/issues

Home Page:https://readthedocs.org/projects/django-autoslug/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to force update / refresh the slug field?

Calzzetta opened this issue · comments

Hi,

I did a model for blog posts and I want to update the slug until the "published" value is False. After that the post owner can update the title but the slug will stay the same. My initial idea was to put this logic inside the save method but I didn't found the "refresh" method from AutoSlugField. How can I solve this?

Regards,
Douglas

@Calzzetta , manually set slug to None and save model, then it will be forced to refresh slug.

You may use post_save or pre_save (for further look at the source code of autoslug about when exactly it is operating) but in general it is a bad idea to change slug !

As far as i see it uses post_save so imho you need to use pre_save where you can set slug to None.

P.S. not tested actually, i will be interested in your results :)

I was wondering about the same thing after adding autoslug to existing project :)

Suggestion of @ArtemBernatskyy worked for me:

players = Player.objects.all()
players_len = len(players)

with transaction.atomic():
  for i, player in enumerate(players):
    print 'Updating slug %d/%d' % (i, players_len)
    player.slug = None
    player.save()

Another way would possibly be to use always_update option:

class Player(models.Model):
    name = models.CharField(max_length=200, unique=True)
    slug = AutoSlugField(populate_from='name', always_update=True)

http://django-autoslug.readthedocs.io/en/latest/fields.html

@UncleVasya do not update in loop better use django update https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.update

(but i haven't tested in this condition)

@ArtemBernatskyy update() will not work here because it doesn't call model's save() method.

And since AutoSlugField isn't nullable, update(slug=None) will fail with DB exception.

Thank you guys!

I removed the 'auto_update' attribute and now I am overwriting the value of the slug every time that I want to update it.