[英]Is it safe to name field as 'id' in Django model?
class MyModel(models.Model):
id = models.IntegerField(primary_key=True)
or 要么
class MyModel(models.Model):
id_ = models.IntegerField(primary_key=True)
According to pep8 single_trailing_underscore_ should be used by to avoid conflicts with Python keyword but having column named id_ would look ugly and possibly cause confusion to someone not familiar with python on database level. 根据pep8,应该使用single_trailing_underscore_来避免与Python关键字冲突,但是名为id_的列看起来很丑陋并且可能导致对数据库级别不熟悉python的人造成混淆。
Django docs use 'id' column name: https://docs.djangoproject.com/en/1.11/ref/models/fields/#uuidfield . Django docs使用'id'列名: https : //docs.djangoproject.com/en/1.11/ref/models/fields/#uuidfield 。
Is it safe to name this field as 'id'? 将此字段命名为“id”是否安全?
Python allows shadowing builtins in any context. Python允许在任何上下文中隐藏内置函数。 Builtins are at the lowest precedence in the LEGB model (local variables, enclosing scopes, global variables, builtins). Builtins在LEGB模型中处于最低优先级(局部变量,封闭范围,全局变量,内置变量)。 At the same time, code in other modules will not be affected by this shadowing; 同时,其他模块中的代码不会受到此阴影的影响; id
will still refer to the builtin in other contexts. id
仍将引用其他上下文中的内置函数。 So it's entirely safe to shadow builtins. 所以影子内置者是完全安全的。 The "real" question is whether it's a Good Idea. “真正的”问题是它是否是一个好主意。 In this case: 在这种情况下:
id()
is one of the less-commonly used builtins. id()
是不太常用的内置函数之一。 .id
field is idiomatic in Django code, and in fact, Django creates this field by default if you don't do so. 在Django代码中使用.id
字段是惯用的,事实上,如果你不这样做,Django会默认创建这个字段。 Yes, it's fine to use id
if you are adding a custom primary key for a Django model, just like in the example you linked to in the docs. 是的,如果要为Django模型添加自定义主键,则可以使用id
,就像在文档中链接的示例一样。 For regular usage however, Django automatically creates an id
field that is defined as 但是,对于常规用法,Django会自动创建一个定义为的id
字段
id = models.AutoField(primary_key=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.