0

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()

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

4 Comments

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

You can set the default like this:

slug = models.SlugField(default=process_slug)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.