Django 查询 - id vs pk [英] Django queries - id vs pk

查看:31
本文介绍了Django 查询 - id vs pk的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写 django 查询时,可以同时使用 id/pk 作为查询参数.

When writing django queries one can use both id/pk as query parameters.

Object.objects.get(id=1)
Object.objects.get(pk=1)

我知道 pk 代表主键,根据 django 的文档,它只是一个快捷方式.但是不清楚什么时候应该使用 id 或 pk.

I know that pk stands for Primary Key and is just a shortcut, according to django's documentation. However it is not clear when one should be using id or pk.

推荐答案

没关系.pk 更独立于实际的主键字段,即您不需要关心主键字段是被称为 id 还是 object_id 或随便.

It doesn't matter. pk is more independent from the actual primary key field i.e. you don't need to care whether the primary key field is called id or object_id or whatever.

如果您的模型具有不同的主键字段,它还可以提供更高的一致性.

It also provides more consistency if you have models with different primary key fields.

这篇关于Django 查询 - id vs pk的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆