You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中使用主键(PK)生成动态URL?

解决方案:将文章URL从Slug改为UUID主键

1. 修改视图函数(views.py)

将视图的参数从slug改为post_id,并更新查询条件以匹配主键:

def DetailView(request, post_id):
    template_name = 'post_detail.html'
    # 通过UUID主键查询文章,也可以用pk=post_id(pk是主键的通用别名)
    post = get_object_or_404(Post, post_id=post_id)
    
    return render(request, template_name, {'post': post})

2. 修改URL配置(urls.py)

将路径中的slug转换器替换为uuid转换器,对应视图的post_id参数:

path('<uuid:post_id>/', views.DetailView, name='post_detail'),  

注:如果你的主键是整数类型,可改用<int:post_id>,这里匹配UUID类型的主键更精准。

3. 修改HTML模板的URL调用

将模板中传递的post.slug替换为post.post_id(或通用的post.pk):

<!-- 方式1:直接使用主键字段名 -->
<p><a href="{% url 'post_detail' post.post_id %}">{{post.content|safe |slice:":10" }}</a></p>

<!-- 方式2:使用通用主键别名pk(推荐,适配任意主键类型) -->
<p><a href="{% url 'post_detail' post.pk %}">{{post.content|safe |slice:":10" }}</a></p>

可选:移除无用的Slug字段

由于网站暂无内容,若确定后续不需要slug字段,可从模型中删除它并执行数据库迁移:

# 修改后的models.py
class Post(models.Model):
    title = models.CharField(max_length=500)
    image = models.ImageField(null=True, blank=True, upload_to='media/')
    content = RichTextField(blank = True, null = True)
    post_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False)
    created_on = models.DateTimeField(auto_now_add=True)
    modified_on = models.DateTimeField(auto_now=True)
    # 移除slug字段
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
    status = models.IntegerField(choices=STATUS, default=0)
    category = models.CharField(max_length=500, choices= categories_list, default='0')

    class Meta:
        ordering = ['-created_on']

    def __str__(self):
        return self.title

执行迁移命令:

python manage.py makemigrations
python manage.py migrate

内容的提问来源于stack exchange,提问作者Sumanh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 22:55:25