【问题标题】:Is there somewhere different between `pk` and `id`?`pk` 和 `id` 之间有什么不同吗?
【发布时间】:2017-11-02 07:10:26
【问题描述】:

看了源码,发现函数使用pk作为关键字来选择数据:

def detail(request, album_id):
    try:
        album = Album.objects.filter(pk=album_id)
    except Album.DoesNotExist:
        raise Http404("Album does not exist")

    context = {
        "album":album,
    }

    return render(request, "music/detail.html", context)

我习惯用id

album = Album.objects.filter(id=album_id)

那么,他们之间有什么不同吗?

【问题讨论】:

标签: python django


【解决方案1】:

在 django 中,id 字段默认为 pk,因此您可以同时使用两者。

区别:

但是你可以手动设置pk然后可能不是id字段

【讨论】:

    猜你喜欢
    • 2010-12-24
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 2019-10-04
    • 2017-11-20
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    相关资源
    最近更新 更多