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
- Slug field does not comes with implicit uniqueness.
get_object_or_404(Blog, pk=id)
must be faster than get_object_or_404(Blog, slug=slug)
.
- Adding a slug field to existing models involves data migration.
so why SlugField()? , apart from the cost of dynamically generating slug, what are the disadvantages of above method ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…