我對網絡開發還不熟悉,但我知道使用UUID作爲模塊的主鍵是一種很好的做法嗎?是否有必要使用UUID作爲PK?
我正在Django中構建一個應用程序,它在URL中顯示一個pk。例如/user/<pk>/<username-slug>/
。然後通過匹配PK找到此URL的用戶。
將順序整數作爲PK的主要關注點是什麼?它似乎像stackoverflow做到這一點。
這是不是有沒有建立到django的原因?
我對網絡開發還不熟悉,但我知道使用UUID作爲模塊的主鍵是一種很好的做法嗎?是否有必要使用UUID作爲PK?
我正在Django中構建一個應用程序,它在URL中顯示一個pk。例如/user/<pk>/<username-slug>/
。然後通過匹配PK找到此URL的用戶。
將順序整數作爲PK的主要關注點是什麼?它似乎像stackoverflow做到這一點。
這是不是有沒有建立到django的原因?
您應該使用主鍵的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衝突後蛞蝓應該是唯一的。它看起來更乾淨,只需要一點魔力。
如果您的應用程序設計正確,則無需擔心。 – 2014-10-01 01:12:18
相關:http://stackoverflow.com/questions/5159413/uuid-versus-auto-increment-number-for-primary-key – 2014-10-01 01:47:37