2014-10-01 27 views
1

我對網絡開發還不熟悉,但我知道使用UUID作爲模塊的主鍵是一種很好的做法嗎?是否有必要使用UUID作爲PK?

我正在Django中構建一個應用程序,它在URL中顯示一個pk。例如/user/<pk>/<username-slug>/。然後通過匹配PK找到此URL的用戶。

將順序整數作爲PK的主要關注點是什麼?它似乎像stackoverflow做到這一點。

這是不是有沒有建立到django的原因?

+1

如果您的應用程序設計正確,則無需擔心。 – 2014-10-01 01:12:18

+0

相關:http://stackoverflow.com/questions/5159413/uuid-versus-auto-increment-number-for-primary-key – 2014-10-01 01:47:37

回答

-1

您應該使用主鍵的UUID,除非有一個重要原因。然而,你真正得到的是沒有UUID的更好的URL結構,我同意這一點。

我遇到了這個問題,我通過製作一個獨特的slu solve來解決它。我將在下面使用的示例是針對具有不同帖子標題的博客。

# 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) 

有你有它,你的URL結構會工作,而不是在URL中的UUID:所以不存在URL衝突後蛞蝓應該是唯一的。它看起來更乾淨,只需要一點魔力。

+0

感謝您的答覆。我應該提到,一個獨特的slu does不適用於我的情況(兩個不同的用戶可能具有相同的名稱)。你可以擴展更多關於爲什麼一個UUID應該用於PK?這對所有型號都適用嗎? – Ben 2014-10-01 03:20:24

+0

你打算使用什麼PK? – awwester 2014-10-01 04:28:05

+0

只是django的默認pk。 – Ben 2014-10-01 04:42:20

相關問題