tags:

views:

34

answers:

3

I added a slug field to my database and now need to go through and add those. I want to run a script that looks at the slug field in the database and if empty generates and saves. Here is what I thought was along the lines, but is not working.

from project.apps.tracks.models import *

def process_slug():  
    if not track.slug:  
        slug = slugify("%s - %s" % (track.name, track.artist)) 
    else:  
        slug = "" 

    super(process_slug, track).save()
A: 

From your posted code it is not evident, that you are actually looping through all your Track objects.

from project.apps.tracks.models import Track
# import for slugify

def process_slug():
    """ Populate slug field, if they are empty. 
    """
    for track in Track.objects.all():
        if not track.slug:  
            slug = slugify("%s - %s" % (track.name, track.artist)) 
            track.slug = slug
            track.save()

One preferred place for such occasionally recurring commands would be under management/commands inside your application.


Another way to implement would be to override your Track model's save method. It would check for emtpy slugs on every save (which is not performant).

The MYYN
Just tried the script and nothing happened in the database?
timg
If you have backups or don't care about data, try removing the `if` clause, so all rows will be affected.
The MYYN
Nothing changed by removing if clause. The field is null in the database not blank.
timg
hard to tell from here, try add logging statements to see what gets actually executed and maybe what not ...
The MYYN
put print statements in but nothing shows up, add the updated code to the page as an answer
timg
as you wish, my lord
The MYYN
A: 

You can set the default like this:

slug = models.SlugField(default=process_slug)
histrio
A: 

Added print statements to the script, but nothing gets logged.

from django.conf import settings   
from django.template.defaultfilters import slugify

from project.apps.tracks.models import Track

def process_slug():
    """ Populate slug field, if they are empty. 
    """
    for track in Track.objects.all(): 
        print "Trying to slugify"
        if not track.slug: 
            print "slug = %s"
            slug = slugify("%s %s" % (track.track, track.artist)) 
            track.slug = slug
            track.save()   
timg
is this an answer?
The MYYN
no this is what I tried, but it isn't working.
timg
I figured it out, was calling it wrong
timg