Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better to save a slug to the DB or generate dynamically?

Tags:

django

slug

I am working on a django project and would like to include a slug at the end of the url, as is done here on stackoverflow.com: http://example.com/object/1/my-slug-generated-from-my-title

The object ID will be used to look up the item, not the slug -- and, like stackoverflow.com, the slug won't matter at all when getting the link (just in displaying it).

Qestion: is there a downside (or upside) to generating the slug dynamically, rather than saving it as an actual database field ?

For example (not real code):

class Widget(models.Model):
    title = models.CharField()

    def _slug(self):
      return slugify(self.title)
    slug = property(_slug)

Rather than using an something like an AutoSlugField (for example) ?

Since my plan is to have it match the title, I didn't know if it made sense to have a duplicate field in the database.

Thanks!

like image 990
thornomad Avatar asked Oct 10 '09 18:10

thornomad


1 Answers

If you're using the slug for decorative (rather than lookup) purposes, generating it dynamically is the best idea.

Additionally, the code sample you posted can be written like this:

@property
def slug(self):
  return slugify(self.title)
like image 190
John Millikin Avatar answered Oct 20 '22 18:10

John Millikin