本文介绍了Django queries - 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 have to care whether the primary key field is called id or object_id or whatever.

如果您有不同主键字段的模型, 。

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

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

10-19 21:09