开发者

Django script add field to database

开发者 https://www.devze.com 2023-01-05 23:34 出处:网络
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 thoug

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 = slugi开发者_如何学运维fy("%s - %s" % (track.name, track.artist)) 
    else:  
        slug = "" 

    super(process_slug, track).save()


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


You can set the default like this:

slug = models.SlugField(default=process_slug)
0

精彩评论

暂无评论...
验证码 换一张
取 消