2

I'm still new to web development, but I understand it's considered good practice to use a UUID as the Primary Key for a module?

I'm building an app in Django which displays a pk in the URL. e.g. /user/<pk>/<username-slug>/. The user for this url is then found by matching the PK.

What is the major concern with having an sequential integers as the PK? It seems like stackoverflow does it.

Is there a reason this wasn't built into django?

Phil McCullick
  • 7,175
  • 2
  • 29
  • 29
Ben
  • 6,986
  • 6
  • 44
  • 71

1 Answers1

0

You should be using the UUID for the primary key unless there is a significant reason not to. However, what you're really getting at is having a better URL structure without the UUID, which I agree with.

I have ran into this problem and I solve it by making a unique slug. The example I'll use below is for a blog with different post titles. The post slugs should be unique so that there are no URL clashes:

# urls.py
# url pretty straightforward, get the post slug from the url and pass it into the view
urlpatterns = patterns('',
    url(r'(?P<post_slug>[\w]+)/$', views.post, name="post"),
)


# views.py
# get the post object based on the slug passed in from the url
def post(request, post_slug):
    '''
    individual blog page
    '''
    post = Post.objects.get(Post, slug=post_slug)

    return render(request, "template.html", {'post':post})


# models.py
# save the unique slug to be used based on the title
from django.db import models
from django.utils.text import slugify

class Post(models.Model):
    '''
    Blog Post data which has a unique slug field
    '''
    title = models.CharField(max_length=50)
    slug = models.SlugField(unique=True, blank=True)

    def save(self, *args, **kwargs):
        # add identifying slug field on save
        self.slug = slugify(self.title) # can also make a custom slugify to take out hyphens
        super(Post, self).save(*args, **kwargs)

And there you have it, your URL structure would work and not have the UUID in the URL. It looks cleaner, just takes a little bit of magic.

awwester
  • 9,623
  • 13
  • 45
  • 72
  • Thanks for the reply. I should have mentioned, a unique slug doesn't work in my case (two different users could have the same name). Can you expand more on why a UUID should be used over a PK? Is this true for all models? – Ben Oct 01 '14 at 03:20
  • what were you planning on using for the pk? – awwester Oct 01 '14 at 04:28
  • Just django's default pk. – Ben Oct 01 '14 at 04:42
  • 1
    I read your question wrong. There is no harm using the sequential id field. It was built into django - the id field is created by default for every model instance. – awwester Oct 02 '14 at 16:13