Django has models.SlugField()
which helps us to create some cool looking urls.
My question is why specifying it as a field
suppose I have this model
class Blog(models.Model):
title = models.CharField()
and if I want to add slug, I could just use
class Blog(models.Model):
title = models.CharField()
def title_slug(self):
return slugify(self.title)
in urls I could just use
(r'^blog/(?P<id>\d+)/(?P<slug>[-\w]+)/$', 'app.views.blog_view'),
and in views
def blog_view(request, id ,slug):
get_object_or_404(Blog, pk=id)
...
urls will look like
example.com/blog/23/why-iam-here/
There are three things that makes me adopt this method
get_object_or_404(Blog, pk=id)
must be faster than get_object_or_404(Blog, slug=slug)
.so why SlugField()? , apart from the cost of dynamically generating slug, what are the disadvantages of above method ?
Why SlugField() in Django? Because:
The big disadvantage of your dynamically generated slug, accepting slugs in urls.py and not using the slug to get the right object? It's bad design.
If you supply and accept slugs, but don't check against them, then you have multiple URLs returning the same content. So /1/useful-slug/ and /1/this-is-a-bs-slug/ will both return the same page.
This is bad because it does not make life easy for humans. Your visitors have to supply an id and something that is redundant. Duplicated pages are search engines nightmare. Which page is the right one? Duplicated pages will end up with a low rank. See https://support.google.com/webmasters/answer/40349?hl=en (last p)
You can argue that you implement your own beautifully generated links consistently, but people and bots guess URLs all the time (see your logfiles). When you accept all slugs then humans and bots always guess right.
Also saving a slug to the db saves processing power. You generate the slug one time and reuse it. What will be more (in)efficient looking up the slug or generating it each time?
Slug fields in the admin are useful to give editors the opportunity to edit the slug. Maybe to supply extra information that is not in the title but still worth mentioning.
Bonus: To update migrated data:
from django.template.defaultfilters import slugify
for obj in Blog.objects.filter(slug=""):
obj.slug = slugify(obj.title)
obj.save()