4

I recently added slug fields to my MySQL database models (I don't know why it didn't occur to me to do this earlier). Now I have a bunch of blank slug fields in my database. I included a save definition in each model

class test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()

    def save(self, *args, **kwargs):
        self.s = slugify(self.q)
        super(test, self).save(*args, **kwargs)

Now I want to write something to populate each record in my models. Any suggestions on what code I can write to perhaps have it cycle through all my models/records and populate the slugs?

An additional complication (though I'm not sure I care a ton about this). I have a field in each model:

last_modified = models.DateTimeField("Last Modified", auto_now=True)

I'd rather not trigger this because the records aren't really being modified. Can I populate the slugs without updating the last_modified fields?

Community
  • 1
  • 1
Ed.
  • 4,439
  • 10
  • 60
  • 78

1 Answers1

2

Well if it isn't a lot of data, and it is just a one off thing, just do it in the shell:

$ python manage.py shell
>>> from my_app.models import Test
>>> for obj in Test.objects.all():
>>>     obj.save()

If you are going to do this a lot, write a custom management command that does this.

As for your auto_now issue, this is the reason I've stopped using auto_now and auto_now_add. Every time I've used them, I've always ripped them out later. In fact, the Django developers have said they consider them deprecated and they probably will be removed in the future. I'd just edit the source code and remove that option before running your command, then either add it back in or replace it with custom save() logic.

Brian Neal
  • 31,821
  • 7
  • 55
  • 59