5

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!

thornomad
  • 6,707
  • 10
  • 53
  • 78

4 Answers4

8

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)
John Millikin
  • 197,344
  • 39
  • 212
  • 226
2

Try making a slug out of the word "café" or "浦安鉄筋家族".

Chances are that it'll look like poo, unless you're really well-prepared.

Sometimes you need the ability to customize slugs.

Rei Miyasaka
  • 7,007
  • 6
  • 42
  • 69
  • +1, Interesting. I think you're suggesting it should be stored (because it may have been customised). – Edmund Aug 06 '10 at 07:33
  • Sorry, yeah, that's what I'm suggesting. I wasn't too clear was I :) – Rei Miyasaka Aug 06 '10 at 07:55
  • 1
    Would you manually slugify the outliers? It's not possible in many designs to manually do that. However if you are doing it based on certain rules to customize slugs, you could code those rules for dynamically generating them too. Am I missing something? – user May 19 '14 at 14:20
1

The downside would be that you're automatically generating the slug every time you render the page. The upside is that you're not taking up space in the database with a field that will never be directly queried against.

Either way is fine, it just depends on your performance vs. space requirements.

Brian Tol
  • 4,149
  • 6
  • 24
  • 27
  • Yea - those were my thoughts. I didn't know if one of these methods was _preferred_ ... maybe it depends on the server. – thornomad Oct 10 '09 at 22:27
  • Both are negligible. 1 millions slugs, 50 bytes each would be 50MB. Computing it would be trivial as well. – user May 19 '14 at 14:22
0

The main downside of generating slugs dynamically is that you miss the ability to customize slugs per-object, eg. make them shorter and prettier. For English titles this can be OK, but for non-English content generated slugs can be ugly.

Mikhail Korobov
  • 21,908
  • 8
  • 73
  • 65